How to merge matrix in a loop?

조회 수: 6(최근 30일)
Akshay Sahu
Akshay Sahu 2022년 10월 28일
댓글: Akshay Sahu 2022년 10월 29일
Suppose I have four matrix
A,B,C and D. These all are (mx3) matrix where m is some number.
and I have to define a number as an user input which is N.
Now I want a merge matrix such that,
for N = 1
New_matrix = [A]
for N = 2
New_matrix = [A
B
C]
for N = 3
New_matrix = [A
B
C
D
A]
for N = 4
New_matrix = [A
B
C
D
A
B
C]
and so on......

채택된 답변

David Hill
David Hill 2022년 10월 28일
A=randi(10,4,3)
A = 4×3
10 2 9 7 7 4 10 5 1 5 9 2
B=randi(10,5,3)
B = 5×3
8 6 1 10 1 9 6 5 9 5 8 8 10 3 3
C=randi(10,6,3)
C = 6×3
1 6 4 9 4 2 7 5 6 9 5 4 3 2 5 1 2 7
D=randi(10,7,3)
D = 7×3
5 8 3 4 9 5 5 3 9 6 7 7 4 9 3 8 5 6 7 9 9
N=2;
newMatrix=generateMatrix(A,B,C,D,N)
newMatrix = 15×3
10 2 9 7 7 4 10 5 1 5 9 2 8 6 1 10 1 9 6 5 9 5 8 8 10 3 3 1 6 4
function newMatrix=generateMatrix(A,B,C,D,N)
n=2*N-1;
s=[size(A,1),size(B,1),size(C,1),size(D,1)];
newMatrix=repmat([A;B;C;D],ceil(n/4),1);
S=sum(s*floor(n/4))+sum(s(1:mod(n,4)));
newMatrix=newMatrix(1:S,:);
end
  댓글 수: 1
Akshay Sahu
Akshay Sahu 2022년 10월 29일
Thank you @David Hill, your algorithm worked as I want.

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

추가 답변(1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2022년 10월 28일
편집: KALYAN ACHARJYA 2022년 10월 28일
% Just example
A=rand(4,3);
B=rand(4,3);
C=rand(4,3);
D=rand(4,3);
data_mat={A,B,C,D}; % Created to handle data easily
N=4 ; % Example or length of data_mat
data=cell(1,N); %Memory Pre-allocation
for i=1:N
data{i}=horzcat(data_mat{1:i});
end
data
data = 1×4 cell array
{4×3 double} {4×6 double} {4×9 double} {4×12 double}
You may look for cellfun also, please do the modification as per requirements.
  댓글 수: 2
Akshay Sahu
Akshay Sahu 2022년 10월 29일
Yes, It's also correct for N=4. But N is not constant in my case. I want to change value of N according to my need.

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

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by