How to loop two vectors in MATLAB?

笑着哭i 提交于 2019-12-02 05:07:50
Yvon

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

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