editing a cell in a loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Max
am 8 Nov. 2015
Bearbeitet: Geoff Hayes
am 8 Nov. 2015
If I have a 1 column cell
x=
'dog'
'at'
'cat'
'four'
'creative'
How do I write code that removes the words based on their length of letters. Like say I input n=1 it removes all words with letter 1 then n=2 it would remove all words with letter 2 so it would remove 'at' then n=3 removes all words with letter 3 so removes 'cat' and 'dog' leaving
x=
'four'
'creative'
Thanks
0 Kommentare
Akzeptierte Antwort
Geoff Hayes
am 8 Nov. 2015
Max - use cellfun to apply a function to each element in your array. In your case, you could use the length function to determine the lengths of each string or to determine which strings are a certain number of characters long. For example, using your x from above
n = 2;
idcs = cellfun(@length(str)==2,x);
will return
idcs =
0
1
0
0
0
which tells us that the second string in x is of length two. We can then remove that string easily enough by doing
x(idcs) = [];
The above call to cellfun takes an anonymous function as its first input parameter
@(str)length(str)==2
where str is a string element from our cell array x. We calculate the length of str and compare it to two, so that the output from this call is logical (true or false).
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!