I'm trying to iterate over a list of strings in MATLAB. The problem is that, inside the 'for' loop, my iterator is considered a 'cell' rather than a string.
for str = {'aaa','bbb'} fprintf('%s\n',str); end ??? Error using ==> fprintf Function is not defined for 'cell' inputs.
What is the correct\elegant way to fix this?
Iterating through strings is same as iterating through a range of numbers. Here we use length() function to provide final value in for loop, and we can also use disp() function to print the output.
The elements in an array can be accessed by using an index number. The index number starts from zero in an array. To add and rearrange the strings in an array we can use plus operator to add strings, join, split, sort functions to rearrange the strings.
Note that Matlab iterates through the columns of list , so if list is a nx1 vector, you may want to transpose it. If you don't know whether list is a column or a row vector, you can use the rather ugly combination (:)' : for elm = list(:)'; %... ;end .
You should call the cell's content via str{1}
as follows to make it correct:
for str = {'aaa','bbb'} fprintf('%s\n',str{1}); end
Here's a more sophisticated example on printing contents of cell arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With