Creating matric of multiple arrays

조회 수: 6(최근 30일)
Nicholas Moung
Nicholas Moung 2021년 1월 20일
댓글: Adam Danz 2021년 1월 20일
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
Nicholas Moung
Nicholas Moung 2021년 1월 20일
This is just an example. The real formulae need the iteration. For instant, a,b,c and d are 1*100 arrays (when x=1:100;), and the matrix Z will be the 2*2 matrix formed by those a,b,c and d and each of the element of this matrix Z must be 1*100 array. And the formulae for a,b,c and d are just examples. Thank you for discussing!

댓글을 달려면 로그인하십시오.

채택된 답변

Bob Thompson
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
Nicholas Moung
Nicholas Moung 2021년 1월 20일
Thank you so much! It does work!

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Adam Danz
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)
(:,:,1) = 5 5 5 0 (:,:,2) = 6 7 9 5 (:,:,3) = 7 9 13 10 (:,:,4) = 8 11 17 15 (:,:,5) = 9 13 21 20 (:,:,6) = 10 15 25 25 (:,:,7) = 11 17 29 30 (:,:,8) = 12 19 33 35 (:,:,9) = 13 21 37 40 (:,:,10) = 14 23 41 45 (:,:,11) = 15 25 45 50 (:,:,12) = 16 27 49 55 (:,:,13) = 17 29 53 60
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
Z =
Z(:,:,1) = 5 5 5 0 Z(:,:,2) = 6 7 9 5 Z(:,:,3) = 7 9 13 10 Z(:,:,4) = 8 11 17 15 Z(:,:,5) = 9 13 21 20 Z(:,:,6) = 10 15 25 25 Z(:,:,7) = 11 17 29 30 Z(:,:,8) = 12 19 33 35 Z(:,:,9) = 13 21 37 40 Z(:,:,10) = 14 23 41 45 Z(:,:,11) = 15 25 45 50 Z(:,:,12) = 16 27 49 55 Z(:,:,13) = 17 29 53 60
  댓글 수: 2
Adam Danz
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.

댓글을 달려면 로그인하십시오.

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by