MATLAB相当于“for s in('foo','bar','baz'):......”?

时间:2013-05-15 19:45:56

标签: matlab

MATLAB等价于(Python的)

for s in ('foo', 'bar', 'baz'):
    do_stuff_with(s)

或者,更好的是,MATLAB相当于

for s in 'foo bar baz'.split():
    do_stuff_with(s)

(我意识到MATLAB不鼓励使用for循环,但我想到的情况是,例如,矢量化操作会非常不切实际。)

2 个答案:

答案 0 :(得分:3)

for s={'foo', 'bar', 'baz'}
  do_stuff_with(s)
end


for s =strsplit('foo bar baz')
  do_stuff_with(s)
end

第二个是Matlab 2013a,但是

答案 1 :(得分:0)

% define your inputs in a cell array
input = {'foo', 'bar', 'baz'};

% You can use "regexp" to split the string
input = regexp('foo bar baz', ' ', 'split');

% Or, if you have Matlab R2013a or newer, you can use "strsplit" to split the string
input = strsplit('foo bar baz');

% use for loop to go over each entry of the cell array
for n=1:length(input)
  s = input{n};
  do_stuff_with(s);
end

% Depending on what "do_stuff_with" does, you may use "cellfun" to run do_stuff_with() for each entry of the cell array
do_stuff_with = @(x) sprintf('word: %s',x);
output = cellfun(do_stuff_with, input);