Borrar filtros
Borrar filtros

How to create code to remove rows from a table

1 visualización (últimos 30 días)
DIMITRA
DIMITRA el 10 de Abr. de 2019
Comentada: DIMITRA el 10 de Abr. de 2019
Hello everyone! I need to remove every row that contains a specific number (let's say 0) from a 2D Table.
How can i create a code PLEASE?
  2 comentarios
Stephen23
Stephen23 el 10 de Abr. de 2019
@DIMITRA: what have you tried so far?
DIMITRA
DIMITRA el 10 de Abr. de 2019
@Stephen Cobeldick First of all thank you very much for the answer!
My table's (DIRP) size is (478,354).
I began with turning those rows entirely to 0.
for i=1:478
for j=1:354
if DIRP(i,j)==0
DIRP(i,:) =0; %if i type DIRP(i,:) =[]; to delete the row, my %table changes size so i tried this first
end
end
end

Iniciar sesión para comentar.

Respuesta aceptada

Bob Thompson
Bob Thompson el 10 de Abr. de 2019
You're on the right track by using logic to identify whether a row contains a 0, but you would be better off marking different rows for zeros, and then removing them all at the end.
check = zeros(478,354); % Create an array to look for checks
rows = []; % Empty array to name rows to remove
for i=1:478
for j=1:354
if DIRP(i,j)==0
check(i,j) =1; % Mark elements as zero
end
end
if sum(check(i,:))>0; % Check row for zeros
rows = [rows; i];
end
end
DIRP = DIRP(~rows,:); % Remove flagged rows
There are a few alternative options to this. The first is to catch the entire logic array at the beginning and then use one loop to go through all rows.
check = DIRP == 0; % Logic array, should be same end result of previous check
rows = [];
for i = 1:478;
if sum(check(i,:))>0; % Check row for zeros
rows = [rows; i];
end
end
DIRP = DIRP(~rows,:); % Remove flagged rows
Alternatively, you can index your output to remove certain rows based on the logic check all at once. It's ultimately doing the same thing as the above codes, just in one line.
reduced = DIRP(DIRP~=any(DIRP==0,2));
The any command searches all of the specified range (set to 'rows' with the '2'). Setting the range of DIRP~=any... means that you are looking for rows which do not contain a 0.
  1 comentario
DIMITRA
DIMITRA el 10 de Abr. de 2019
Problem solved, you've been very helpfull really.
Thank you very much!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by