Creating matric of multiple arrays
Show older comments
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 Comments
Bob Thompson
on 20 Jan 2021
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.
Nicholas Moung
on 20 Jan 2021
Accepted Answer
More Answers (1)
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 Comments
Nicholas Moung
on 20 Jan 2021
Adam Danz
on 20 Jan 2021
No problem, I'm glad you found solutions!
For what it's worth, the reshape solution is most efficient and only requires 1 line.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!