0

什么是 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 循环,但我想到的情况是,例如矢量化操作非常不切实际。)

4

2 回答 2

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


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

第二个是用于 Matlab 2013a,不过

于 2013-05-15T19:51:33.457 回答
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);
于 2013-05-15T20:11:47.313 回答