【问题标题】:MATLAB's equivalent of "for s in ('foo', 'bar', 'baz'): ..."?MATLAB 相当于“for s in ('foo', 'bar', 'baz'): ...”?
【发布时间】:2013-05-15 19:45:55
【问题描述】:

什么是(Python)的 MATLAB 等价物

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

?

或者,更好的是,MATLAB 的等价物是什么

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

?

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

【问题讨论】:

    标签: matlab


    【解决方案1】:
    for s={'foo', 'bar', 'baz'}
      do_stuff_with(s)
    end
    
    
    for s =strsplit('foo bar baz')
      do_stuff_with(s)
    end
    

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

    【讨论】:

    • 请注意,在 FOR 循环中,s 可能是一个单元素元胞数组。
    • 确实:以上内容真的应该用do_stuff_with(s{1}) 写(我必须说,这很烦)...
    【解决方案2】:
    % 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多