Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop with strings in Matlab

Tags:

foreach

matlab

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

like image 941
SIMEL Avatar asked Mar 22 '12 16:03

SIMEL


1 Answers

Or you can do:

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

Result:

cow
dog
cat
like image 54
Oli Avatar answered Oct 20 '22 07:10

Oli