foreach loop with strings in Matlab

前端 未结 3 2042
盖世英雄少女心
盖世英雄少女心 2021-02-20 17:43

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\';
  else         


        
相关标签:
3条回答
  • 2021-02-20 18:24

    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
    
    0 讨论(0)
  • 2021-02-20 18:25

    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
    
    0 讨论(0)
  • 2021-02-20 18:36

    Or you can do:

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

    Result:

    cow
    dog
    cat
    
    0 讨论(0)
提交回复
热议问题