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

3 Ansichten (letzte 30 Tage)
Rocco am 30 Mär. 2023
Kommentiert: Rocco am 30 Mär. 2023
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 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

John D'Errico am 30 Mär. 2023
TSLA = rand(366,7);
TSLA(TSLA(:,4) == 0,:) = [];
One line. No loops.
##### 1 KommentarKeine anzeigenKeine ausblenden
Rocco am 30 Mär. 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!

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Image Analyst am 30 Mär. 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 Kommentare2 ältere Kommentare anzeigen2 ältere Kommentare ausblenden
Rocco am 30 Mär. 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.

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Logical in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!