Creating matric of multiple arrays
7 次查看(过去 30 天)
显示 更早的评论
x=0:12;
k=5;
a=k+x;
b=k+2x;
c=k+4x;
d=kx;
I'd like to create 2*2 matrix of four arrays (a,b,c,d).
Z=[a b; c d];
How could I realize this task by using for loop? Or do you have any other way to realize it? I ask for your advice! Thank you in advance!
2 个评论
Bob Thompson
2021-1-20
What are you looking to loop? Your setup looks fine for a single iteration, so 'looping' should just be a matter of identifying what you want to change, and putting it, and the affected equations, inside a loop.
采纳的回答
Bob Thompson
2021-1-20
You should be able to accomplish what you're looking for with some matrix indexing, no loop necessary.
x = 1:100;
k = 12;
a = x + k; % Makes a 100x1 size array, 13:112
b = 2*x + k; % Makes a 100x1 size array following the same formula
c = 4*x + k;
d = x * k;
% Adding a third dimension of Z allows you to basically stack each of the elements of a, b, c, and d
% into the one 2x2 format. Z(:,:,1) is a 2x2 of [a(1), b(1); c(1), d(1)], and each subsequent 'sheet'
% takes you to the next set of elements in the four matrices.
Z(1,1,:) = a;
Z(1,2,:) = b;
Z(2,1,:) = c;
Z(2,2,:) = d;
更多回答(1 个)
Adam Danz
2021-1-20
编辑:Adam Danz
2021-1-20
Perhaps this (scroll down to see vectorized version)?
x=0:12;
k=5;
a=k+x;
b=k+2*x;
c=k+4*x;
d=k*x;
Z = nan(2,2,numel(x));
for i = 1:numel(x)
Z(:,:,i) = [a(i) b(i); c(i) d(i)];
end
disp(Z)
If so, you don't need a loop.
Z = reshape([a;c;b;d],2,2,numel(x)) % Assuming a,b,c,d are row vectors
2 个评论
Adam Danz
2021-1-20
No problem, I'm glad you found solutions!
For what it's worth, the reshape solution is most efficient and only requires 1 line.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!