Finding the first instance of a value in an array
89 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Pelajar UM
am 29 Okt. 2021
Bearbeitet: Pelajar UM
am 30 Okt. 2021
I have an array with many rows and many columns. I want to search the array row by row, find the first instance of a value that is above 170 (yellow cells below) and then store the colum index it was found in (green cells below) in a new array. If there are no values above 170, then return 0 as the index.
This should explain it:
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 29 Okt. 2021
YourArray = randi([100 180], 10, 20)
idx = sum(cumprod(YourArray <= 170, 2),2) + 1;
idx( idx == size(YourArray,2) + 1 ) = 0;
idx
1 Kommentar
Weitere Antworten (1)
Chris
am 29 Okt. 2021
A = magic(5)
for idx = 1:size(A,1)
test = find(A(idx,:)>22,1);
if isempty(test)
test = 0;
end
colidxs(idx,1) = test;
end
colidxs
A is your array, and replace 22 with 170.
1 Kommentar
Chris
am 29 Okt. 2021
For something a bit faster, try
A = magic(5);
colidxs = rowfun(@findidx,table(A))
function idx = findidx(row)
idx = find(row > 22,1);
if isempty(idx)
idx = 0;
end
end
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!