delete cell and replace with remaining cells in matlab
2 次查看(过去 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!