delete cell and replace with remaining cells in matlab

12 views (last 30 days)
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.

Answers (1)

Voss
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
Index exceeds the number of array elements. Index must not exceed 4.
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);
A = 1×4
1 2 4 5
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);
semifinalcode = 1×2 cell array
{["(ok)"]} {["(booey)"]}

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!