Using a for loop to split a matrix by rows

Hi,
I've got an issue splitting a matrix into two seperate matrices using a For loop for rows that have the number 11 in it and one that doesnt.
The matrix X = [1 2 3 11 5; 77 1 2 11 3; 1 2 3 4 5; 1 2 3 4 5; 1 11 3 4 5; 1 2 3 4 5]
I've tried the following..
for i=1:length(J)
if J(i,:)==11
A(i,:)=J
else J(i,:)~=11
B(i,:)=J
end
end
end

Antworten (1)

Star Strider
Star Strider am 4 Okt. 2021
No loops necessary —
X = [1 2 3 11 5; 77 1 2 11 3; 1 2 3 4 5; 1 2 3 4 5; 1 11 3 4 5; 1 2 3 4 5]
X = 6×5
1 2 3 11 5 77 1 2 11 3 1 2 3 4 5 1 2 3 4 5 1 11 3 4 5 1 2 3 4 5
X11 = X(any(X==11,2),:)
X11 = 3×5
1 2 3 11 5 77 1 2 11 3 1 11 3 4 5
Xnot11 = X(~any(X==11,2),:)
Xnot11 = 3×5
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
This approach simply uses logical indexing. See the documentation for the any function to udnerstand how it works.
.

2 Kommentare

John Smith
John Smith am 4 Okt. 2021
Bearbeitet: John Smith am 4 Okt. 2021
Without loop I was also able to do it with
K = X == 11;
A = X(sum(K,2)>0,:)
B = X(~sum(K,2)>0,:)
For my assignment however I have to do it with a loop unfortunately
Star Strider
Star Strider am 4 Okt. 2021
O.K.
Frist, don’t use the length function here. It returns the greatest dimension, and that may not always be the number of rows. Use the size function instead, and specify the required dimension.
Second, it is still possible to use the any function in the loop. The alternative is to use nested loops, and scan the elements of each row to see if any of them equal 11, then store the row appropriately if they do.
.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2021b

Gefragt:

am 4 Okt. 2021

Kommentiert:

am 4 Okt. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by