Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a list of strings in MATLAB

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?

like image 423
wanderingbear Avatar asked May 21 '12 14:05

wanderingbear


People also ask

How do I iterate through a string in Matlab?

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.

How do you access a string array in Matlab?

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.

How do I iterate a vector in Matlab?

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 .


1 Answers

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.

like image 83
petrichor Avatar answered Nov 03 '22 01:11

petrichor