How to loop two vectors in MATLAB?

别说谁变了你拦得住时间么 提交于 2019-12-02 09:49:26

问题


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', 'C']
two = [1, 2, 3]

for i, j in zip(one, two):
    print i, j

for j, i in enumerate(one):
    print i, two[j]

Gives

>>> 
A 1
B 2
C 3
A 1
B 2
C 3

In MATLAB it's possible to do

one = {'A' 'B' 'C'};
two = [1 2 3];

for i = 1:1:length(one)
  printf('%s %i\n', one{i}, two(i));
endfor

j = 1;
for i = one
  printf('%s %i\n', i{1}, two(j));
  j = j + 1;
endfor

giving

A 1
B 2
C 3
A 1
B 2
C 3

So is one of those two options the common way how one would do it in MATLAB, i. e. to loop through several vectors "in parallel" or is there another, maybe better way?

Bonus:

two = [1 2 3];
two = [1, 2, 3];

Both of these lines give the same output in the upper MATLAB program. Whats the difference?


回答1:


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



来源:https://stackoverflow.com/questions/25225498/how-to-loop-two-vectors-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!