Trying to split a Matrix into two matrices dependant on the value of row elements.

Hi there,
Ultimately I am trying to split Matrix A into two matrices. One Matrix containing the rows of A with the number 55 and one containing the rows of Matrix A without the number 55.
The below script is how far I have got. This is my first attempt at just trying to delete the rows containing the value 55.
Additionally I don't know how I would even form two new matrices from the sub-divided A?
>> A=[1 2 3 55 5 ;55 1 2 55 3 ;1 2 3 4 5 ;1 2 3 4 5 ;1 55 3 4 5 ;1 2 3 4 5];
>> for m=1:length(A(:,1))
for n=1:length(A(1,:))
if A(m,n)==55
A(m,:)=[];
end
end
end
Index in position 1 exceeds array bounds (must not exceed 4).
>> A
A =
55 1 2 55 3
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
I don't understand why this script it not removing the row with two elements with value = 55. And the error message!
Any help will be gratefully received
Kind Regards

2 Comments

Classical logical error of someone who start programming: When you delete a row the matrix shrinks but you still loop until the last row of the original.
If you make the outer loop backward it would be OK.
There is another error more subtle in your code. Let you figure out what.
Hi Bruno
Thanks for your rapid reply, I will give this a try tomorrow morning. Saying its a classical error actually fills me with a bit more confidence. Haha
Much appreciated

Sign in to comment.

 Accepted Answer

You reduce the size of A in the loop!
Here is the matlab way to go, split in multiple lines, so you can follow its logic:
A = [1 2 3 55 5 ;55 1 2 55 3 ;1 2 3 4 5 ;1 2 3 4 5 ;1 55 3 4 5 ;1 2 3 4 5];
is55 = A==55
tf = any(is55, 2)
Bwith55 = A( tf, :)
Bwithout55 = A(~tf, :)

1 Comment

Hi Jos
Brilliant, thanks so much for the quick response. Will give this a try when I get to the library tomorrow.
Kind Regards

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!