delete cell and replace with remaining cells in matlab
4 views (last 30 days)
Show older comments
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.
1 Comment
Dyuman Joshi
on 15 Jan 2022
Your code looks correct for the thing you are trying to do. What exactly is the problem you are facing?
Maybe try isequal() rather than directly comparing(?)
Answers (1)
Voss
on 15 Jan 2022
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);
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!