Create a submatrix with rows corresponding to a specified value in the first column of a matrix
이전 댓글 표시
I have this matrix:
A=[ 1 10 2000; 0 25 3000; 1 15 1080; 0 29 2500]
with the first column containing 0 and 1.
I'd like to have two submatrices, the first containing only the value in the third column corresponding to the 0s in the first column, the other one for the 1s.
I created this code to do this:
A1=A(A==0,end)
A2=A(A==1,end)
But I would like to know if there's any possible day to end up with this result using loops.
I created this loop:
for i=1:4
if A(i)<1
A(A==0,end)
else
A(A==1,end)
end
end
But it gives me 4 answers, when I need only 2, the two submatrices I want to find.
How can I make a loop ending up in just two submatrices, to achieve the same result obtained with the former code?
Thank you.
채택된 답변
추가 답변 (1개)
Guillaume
2014년 10월 1일
First, your non-loop code only works because you don't have any 0 or 1 in any other column than the first. If you had a 0 or 1 in column 2 onward, you'd get an index exceeds matrix dimension error. The proper non loop syntax is:
A1 = A(A(:, 1) == 0, end); %make sure you're only comparing the 1st column
A2 = A(A(:, 1) == 1, end);
I'm not sure why you'd want to use loop, which is going to be slower but one way to do it:
A1 = []; A2 = [];
for r = 1:size(A, 1)
switch A(r, 1)
case 0
A1(end+1) = A(r, 3);
case 1
A2(end+1) = A(r, 3);
end
end
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!