delete cell and replace with remaining cells in matlab
조회 수: 4 (최근 30일)
이전 댓글 표시
for x=1:length(semifinalcode)
newtrim="("+trim_Ainstruction+")";
if semifinalcode{x}==newtrim
semifinalcode{x}={};
out=x;
semifinalcode=semifinalcode(~cellfun('isempty',semifinalcode));
end
end
I want to delete purticular cell after if loop and replace with remaining data in that array, but failed. tried in the above way. can anyone help? where 'semifinal ' datatype is cell type array.
댓글 수: 0
답변 (1개)
Voss
2022년 1월 15일
If you delete elements from an array (of any type including a cell array) from within a for loop that loops over the elements of that same array, you're going to run into the situation where your loop index exceeds the size of the array, because the array decreases in size as the loop goes along, but the indexes to use are set when the loop starts. For example, if I make a vector [1 2 3 4 5], then use a for loop to remove any 3's, I'll get an error when I try to check the 5th element because by that time the array only has 4 elements:
try
A = [1 2 3 4 5];
for i = 1:numel(A)
if A(i) == 3
A(i) = [];
end
end
catch ME
display(ME.message);
end
Instead, you can mark the elements for deletion during the loop, but then delete them all only once the loop has completed:
A = [1 2 3 4 5];
to_be_deleted = false(size(A));
for i = 1:numel(A)
if A(i) == 3
to_be_deleted(i) = true;
end
end
A(to_be_deleted) = [];
display(A);
So in your case you might try something like this:
semifinalcode = {"(ok)" "(baba)" "(booey)"};
trim_Ainstruction = "baba";
to_be_deleted = false(size(semifinalcode));
for x = 1:numel(semifinalcode)
newtrim = "(" + trim_Ainstruction + ")";
if semifinalcode{x} == newtrim
to_be_deleted(x) = true;
end
end
% out = find(to_be_deleted); % how it should be?
out = find(to_be_deleted,1,'last'); % how it was
semifinalcode(to_be_deleted) = [];
display(semifinalcode);
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!