How to change a certain array cell depending on its length
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Nom
el 19 de Sept. de 2019
Comentada: Nom
el 19 de Sept. de 2019
Hello,
I currently have this very simple code:
if strlength(A) >= 250
A = [];
end
My objective is for every cell that A has which is larger than 250 characters, make that specific array row 0.
e.g. ( The 12th row of array A has more than 250 characters in it, thus it should become 0 after the code runs)
However, my problem is that the program just skips over the if statement as if it's false when in reality I have characters which go beyond 250.
I tried implementing the cellfun into this as well just in case every row of the array isn't being checked.
if cellfun(@strlength, A)>=250
A = [];
end
but still the same problem.
I know the if statement isn't false because upon running just
strlength(A) >= 250
I have a whole list of 0's (which corespond to characters under 250) and some 1's (which are those above 250)
0 comentarios
Respuesta aceptada
Adam Danz
el 19 de Sept. de 2019
Editada: Adam Danz
el 19 de Sept. de 2019
If 'A' is a cell array of character vectors and you'd like to replace cells that have a length greater than 250 with an empty char array,
A(strlength(A)>250) = {''};
For string arrays (ie, ["abc", "def", "ghi" ...],
A(strlength(A)>250) = "";
8 comentarios
Adam Danz
el 19 de Sept. de 2019
If A is a cell array of paths and you're trying to eliminate the paths and keep the filenames, this would be a better approach:
[~,filenames] = cellfun(@fileparts,A,'UniformOutput',false)
Más respuestas (1)
Fabio Freschi
el 19 de Sept. de 2019
Editada: Fabio Freschi
el 19 de Sept. de 2019
mask = strlength(A) > 250;
A(mask) = cellfun(@(i) '', A(mask), 'uniform', 0);
using a strategy similar to the solution used here https://www.mathworks.com/matlabcentral/answers/366514-using-conditional-statements-inside-cellfun
Ver también
Categorías
Más información sobre Characters and Strings 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!