10
votes

I want to create a loop that will iterate over several strings, but unable to do so in Matlab.

What works is:

for i=1:3
  if (i==1)
    b='cow';
  elseif (i==2)
    b='dog';
  else
    b='cat';
  end

  disp(b);
end

and the result is:

cow
dog
cat

But what I want is something more elegant that will look like:

for i=['cow','dog','cat']
  disp (i);
end

and give the same result.

Is there an option in Matlab to do this?

ADDITION:

I need the words as strings later on to use and not just to display (the disp was just as an example). I've tried to use cell arrays in my real program:

clear all;
close all;
clc;

global fp_a
global TEST_TYPE
global SHADE_METHODE

for fp_a=11:24
for shade={'full','fast'}
    SHADE_METHODE=shade(1);
    for test={'bunny','city'}
        TEST_MODE=test(1);
        fprintf ('fp_a:%d | test: %s | shade: %s',fp_a,TEST_TYPE,SHADE_METHODE);
        ray_tracing;
    end
end
end

It doesn't work as the values stay as cells and not strings I get the error message:

??? Error using ==> fprintf Function is not defined for 'cell' inputs.

*-I don't really need the fprintf I just use it to check that the values are correct.

**-ray_tracing is my code that uses the values of the strings

3
The problem in the addition is just syntax. You need to use the curly braces - test{1} - to extract the char array from the cell, not normal parentheses - test(1) - which just select the first cell in the array, effectively doing nothing here. Check Oli's example code again; note he's using the curly braces in i{1}. (Also, don't use globals if you can avoid it.) - Andrew Janke
You should use SHADE_METHODE=shade{1}; instead of SHADE_METHODE=shade(1); - Oli

3 Answers

31
votes

Or you can do:

for i={'cow','dog','cat'}
   disp(i{1})
end

Result:

cow
dog
cat
6
votes

Your problems are probably caused by the way MATLAB handles strings. MATLAB strings are just arrays of characters. When you call ['cow','dog','cat'], you are forming 'cowdogcat' because [] concatenates arrays without any nesting. If you want nesting behaviour you can use cell arrays which are built using {}. for iterates over the columns of its right hand side. This means you can use the idiom you mentioned above; Oli provided a solution already. This idiom is also a good way to showcase the difference between normal and cell arrays.

%Cell array providing the correct solution
for word = {'cow','dog','cat'}
    disp(word{1}) %word is bound to a 1x1 cell array. This extracts its contents.
end

cow
dog
cat


%Normal array providing weirdness
for word = ['cow','dog','cat'] %Same as word = 'cowdogcat'
    disp(word) %No need to extract content
end

c
o
w
d
o
g
c
a
t
2
votes

Sure! Use cell arrays for keeping strings (in normal arrays, strings are considered by character, which could work if all strings have the same length, but will bork otherwise).

opts={'cow','dog','cat'}
for i=1:length(opts)
    disp(opts{i})
end