How can i call the first point that appears in a matrix with a certain value?

8 Ansichten (letzte 30 Tage)
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 Kommentar
dpb
dpb am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

John D'Errico
John D'Errico am 9 Jan. 2022
A=[1 2 3; 4 5 6;7 6 9;6 4 7;9 0 10;3 4 6]
A = 6×3
1 2 3 4 5 6 7 6 9 6 4 7 9 0 10 3 4 6
firstappearance = find(A == 6,1,'first')
firstappearance = 4
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)
rowind = 4
colind = 1
If you wanted MATLAB to look at the rows first, then transpose the matrix before doing the find operation.

Image Analyst
Image Analyst am 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]
A = 6×3
1 2 3 4 5 6 7 6 9 6 4 7 9 0 10 3 4 6
[rows, columns] = find(A == 6)
rows = 4×1
4 3 2 6
columns = 4×1
1 2 3 3
So you have 6's at (row, column) = (4, 1) and (3, 2) and (2, 3) and (6, 3).

Matt J
Matt J am 9 Jan. 2022
Bearbeitet: Matt J am 9 Jan. 2022
A=[1 2 3; 4 5 6;7 6 9;6 4 7;9 0 10;3 4 6];
[~,firstappearance]=max(A==6)
firstappearance = 1×3
4 3 2

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by