How to remove rows?

조회 수: 18 (최근 30일)
Justyna Slawska
Justyna Slawska 2016년 12월 15일
답변: Steven Lord 2016년 12월 15일
mydata = importdata('data.txt'); A=mydata;
nRows = size(A, 1);
nColumns = size(A,2);
for i=1: nRows
if (nnz(A(i,:)<3540) == 15)
A(i,:)=[];
end
end

채택된 답변

José-Luis
José-Luis 2016년 12월 15일
You don't need to loop
A(sum(A < 3540, 2) == 15,:) = [];
  댓글 수: 1
Justyna Slawska
Justyna Slawska 2016년 12월 15일
thx :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2016년 12월 15일
If you must loop (a requirement of a homework assignment, for instance) inside the loop you should not actually delete the rows of the matrix. Instead record which rows need to be deleted and delete all of them after the loop is complete. Why?
x = 1:10;
n = numel(x);
for k = 1:n
fprintf('x contains %d elements, processing element %d of %d.\n', ...
numel(x), k, n);
if mod(x(k), 2) == 0
x(k) = [];
end
end
In this code you're shortening x every other iteration, and eventually you "walk off the end" of the array. Unlike Bugs Bunny, MATLAB notices immediately. Instead of chopping pieces off the array immediately, identify which pieces need to be removed then remove then once identification is complete.
x = 1:10;
n = numel(x);
toBeDeleted = false(size(x));
for k = 1:n
fprintf('x contains %d elements, processing element %d of %d.\n', ...
numel(x), k, n);
if mod(x(k), 2) == 0
toBeDeleted(k) = true;
end
end
x(toBeDeleted) = []

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by