How to create code to remove rows from a table

1 次查看(过去 30 天)
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 个评论
DIMITRA
DIMITRA 2019-4-10
@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

请先登录,再进行评论。

采纳的回答

Bob Thompson
Bob Thompson 2019-4-10
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by