How do I remove every row that has a zero in it?
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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...
0 Commenti
Risposta accettata
Più risposte (1)
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
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.
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!