如何在MATLAB中循环两个向量? [英] How to loop two vectors in MATLAB?

查看:744
本文介绍了如何在MATLAB中循环两个向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,可以使用zip循环多个矢量,或者使用enumerate来获取循环矢量的当前索引,就像这样

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]

给予

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

在MATLAB中可以做到

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

给予

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

所以这两个选项之一是在MATLAB中如何做到这一点的常用方法. e.可以并行"遍历多个向量,还是还有另一种也许更好的方法?

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?

奖金:

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

这两行都在上层MATLAB程序中提供了相同的输出.有什么区别?

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

推荐答案

在Matlab中使用printffprintf很好.您第一种方法的Matlab代码是

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

也可以将字符串放入单元格数组中,而无需任何for循环.

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)

奖金:

>> 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
>> 

奖金2:

使用ij是不好的.请参阅-在Matlab中将i和j用作变量

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

这篇关于如何在MATLAB中循环两个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆