Clear Filters
Clear Filters

Create a submatrix with rows corresponding to a specified value in the first column of a matrix

6 views (last 30 days)
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.

Accepted Answer

Nalini Vishnoi
Nalini Vishnoi on 1 Oct 2014
Edited: Nalini Vishnoi on 1 Oct 2014
The loop is producing 4 answers since for each value of i, one matrix is created. You need a way to eliminate the rows that have already been selected from matrix A.
It can be done in several possible ways, one of which is provided below:
ind = [];
for i=1:4
if(ismember(i,ind)) % if the row has already been selected, skip
continue;
end
if A(i)<1
indtemp = find(A(:,1)==0); % keeps the record of selected rows in A
A(indtemp,end)
else
indtemp = find(A(:,1)==1); % keeps the record of selected rows in A
A(indtemp,end)
end
ind = [ind ; indtemp];
end

More Answers (1)

Guillaume
Guillaume on 1 Oct 2014
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
  1 Comment
Grayfox
Grayfox on 1 Oct 2014
The non loop syntax is surely better, but I wanted to see if there was any way to get to the same result with a loop. Thank you for the correction of the non loop syntax.

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!