delete cell and replace with remaining cells in matlab
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Voss
el 15 de En. de 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);
1 comentario
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!