How do I remove every row that has a zero in it?

2 visualizzazioni (ultimi 30 giorni)
I have a 366x7 matrix, and I'm trying to remove each row that has a zero in it, I would prefer to use for loops instead of some built-in function.
so for example
TSLA = rand(366,7)
for col = 1:1:size(TSLA,1)
if TSLA(col,4) == 0
TSLA(col,:) = []
end
end
for whatever reason it removes like 61 rows, but leaves like 20 or so with zeros.
Then it says "Index in position 1 exceeds array bounds. Index must not exceed 305." Even though the initial matrix is 366...

Risposta accettata

John D'Errico
John D'Errico il 30 Mar 2023
TSLA = rand(366,7);
TSLA(TSLA(:,4) == 0,:) = [];
One line. No loops.
  1 Commento
Rocco
Rocco il 30 Mar 2023
Awesome, worked perfectly, I was trying to do something similar in my testing where I searched for all the rows with 0 in them but I couldn't figure out how, thank you!

Accedi per commentare.

Più risposte (1)

Image Analyst
Image Analyst il 30 Mar 2023
Try this:
% Check which rows have a zero in one or more columns:
zeroRows = any(TSLA == 0, 2); % Logical index. Equals true if a zero in the row, false if no zero in the row.
% Delete those rows:
TSLA(zeroRows, :) = []; % Delete the row by setting all column values of the row to null.
  3 Commenti
Image Analyst
Image Analyst il 30 Mar 2023
OK, just be aware that the answer you accepted does not "remove every row that has a zero in it" like you asked for. It only removes the row if there is a zero in column 4. The other columns are not checked like in my answer.
OK, since this was a homework problem, and your professor told you explicitly not to use anyone's code other than your own, you should not use John's or my answer or you could get into trouble. I will tag the question as homework, since you forgot. Normally when the student tags it as homework we know not to give complete solutions so the student won't get into trouble.
What you should do is like you tried originally but you need to check all the columns, not just column 4, like this:
if TSLA(col, 1) == 0 || TSLA(col,2) == 0 || etc.
Rocco
Rocco il 30 Mar 2023
I should've given more context, the reason I'm only checking column 4 is because columns 4-7 will all be 0 if column 4 is a 0, the problem is a stock readout for a given day and month.
Furthermore, my professor allows me to have help as long as I cite it, for example we're allowed to go into the MATLAB forums etc. I have asked him about this before, and he said it's alright.

Accedi per commentare.

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by