How can i call the first point that appears in a matrix with a certain value?
8 views (last 30 days)
Show older comments
How can I create a cicle that reads a matrix and gives back the matrix line with the first appearence in the matrix of a certain value
A=[1 2 3; 4 5 6;7 6 9;6 4 7;9 0 10;3 4 6]
[lin col]=size(A)
for i= 1:lin
for j= 1:col
if A(i,j)==6
firstappearence = i
end
end
end
I tried this way however once there is more than one 6 in the matrix firstappearence value would be incorrect. Can you help on this please?
1 Comment
dpb
on 9 Jan 2022
Look at the break instruction...altho NB: it only stops execution of the one loop; as constructed your code will need some additional logic to terminate the second loop.
An alternative to avoid looping could be
>> A=[1 2 3; 4 5 6;7 6 9;6 4 7;9 0 10;3 4 6];
>> MAGICNUMBER=6;
>> [c,r]=find(A.'==6,1)
c =
3.00
r =
2.00
>>
Also above NB: the transpose of A since MATLAB storage/search order is by column. Transposing is then same as searching by row; but then also have to reverse the output variables to refer back to the original array order.
Answers (3)
John D'Errico
on 9 Jan 2022
A=[1 2 3; 4 5 6;7 6 9;6 4 7;9 0 10;3 4 6]
firstappearance = find(A == 6,1,'first')
So the first appearance of a 6 in that matrix is actually the 4th element in the matrix, in the sequence MATLAB stores the elements of a 2-dimensional matrix. Thus the 4th row, first column.
[rowind,colind] = ind2sub(size(A),firstappearance)
If you wanted MATLAB to look at the rows first, then transpose the matrix before doing the find operation.
0 Comments
Image Analyst
on 9 Jan 2022
"I tried this way however once there is more than one 6 in the matrix firstappearence value would be incorrect."
So, if you want ALL occurrences you can also use find(). Just don't tell it 'first', and get both outputs instead of only 1 output.
A=[1 2 3; 4 5 6;7 6 9;6 4 7;9 0 10;3 4 6]
[rows, columns] = find(A == 6)
So you have 6's at (row, column) = (4, 1) and (3, 2) and (2, 3) and (6, 3).
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!