How can i use a for loop based on a row value

I had an original matix;
A = [ 1 a b c
2 d e f
3 g h i
4 j k l ]
which i sorted by rows as;
A = [ 1 a b c
3 g h i
2 d e f
4 j k l ]
later on a for loop i want to use a specific value from A (sorted), based on the first value of each row, and not based in the number of the iteraition.
for examble
for i = 1:3
B (i) = A(i,2)
endfor
when i = 2 (second iteration)
it will return the value g ( A(2,2) ), but i want it to show the value; d ,which is the second value of the row with first corresponding number.

 Accepted Answer

a = 100; b = 200; c = 300;
d = 101; e = 201; f = 301;
g = 102; h = 202; i = 302;
j = 103; k = 203; l = 303;
A = [ ...
1 a b c; ...
2 d e f; ...
3 g h i; ...
4 j k l; ...
]
A = 4×4
1 100 200 300 2 101 201 301 3 102 202 302 4 103 203 303
sortrows(A)
ans = 4×4
1 100 200 300 2 101 201 301 3 102 202 302 4 103 203 303
It's not clear how sorting A by rows gets you the new A, but let's just say now you have the new A:
A = [ ...
1 a b c; ...
3 g h i; ...
2 d e f; ...
4 j k l; ...
]
A = 4×4
1 100 200 300 3 102 202 302 2 101 201 301 4 103 203 303
for i = 1:3
B(i) = A(i,2);
end % endfor is not a MATLAB keyword
B
B = 1×3
100 102 101
disp(B(2) == d);
0
for i = 1:3
B(i) = A(A(:,1) == i,2);
end
B
B = 1×3
100 101 102
disp(B(2) == d)
1

More Answers (0)

Community Treasure Hunt

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

Start Hunting!