How to loop two vectors in MATLAB?

后端 未结 1 1393
说谎
说谎 2021-01-23 17:28

In python one can use zip to loop multiple vectors or enumerate to get the current index of the looped vector like so

one = [\'A\', \'B         


        
相关标签:
1条回答
  • 2021-01-23 18:16

    Using printf, or fprintf in Matlab, is pretty good. The Matlab code for your first approach is

    one = {'A' 'B' 'C'};
    two = [1 2 3];
    
    for ii = 1:length(one)
      fprintf('%s %i\n', one{ii}, two(ii));
    end
    

    It's also possible to put the strings into a cell array, without any for loop.

    s = cellfun(@(a,b) [a,' ',b], one', ...
        arrayfun(@num2str, two', 'UniformOutput', false),....
        'UniformOutput', false)
    

    Bonus:

    >> A = [1;2;3]   
    A =
         1
         2
         3
    >> A = [1 2 3]   
    A =
         1     2     3
    >> A = [1,2,3]   
    A =
         1     2     3
    >> A = [1,2,3;4 5 6;7,8 9]
    A =
         1     2     3
         4     5     6
         7     8     9
    >> 
    

    Bonus 2:

    Using i and j is bad. See - Using i and j as variables in Matlab

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