Shvet Chakra
Shvet Chakra

Reputation: 1043

How to merge two matrices of different dimensions in matlab

I like to merge two matrices of different dimensions in MATLAB without using loops as I have done it with loops.

The image below shows what I want to achieve.

I also tried this link, but this is not what I want: Merging two matrices of different dimension in Matlab?

Here is my attempt to do it with loops:

A=zeros(2,9)-1;
B=ones(6,3);
disp(A);
disp(B);
C=zeros(max(size(A,1),size(B,1)),max(size(A,2),size(B,2)));

for i=1:1:size(A,1)
    C(i,:)=A(i,:);
end
for i=1:1:size(B,2)
    C(:,i)=B(:,i);
end
disp(C);

The desired output should be like this:

A:
    -1    -1    -1    -1    -1    -1    -1    -1    -1
    -1    -1    -1    -1    -1    -1    -1    -1    -1

B:
     1     1     1
     1     1     1
     1     1     1
     1     1     1
     1     1     1
     1     1     1

C:
     1     1     1    -1    -1    -1    -1    -1    -1
     1     1     1    -1    -1    -1    -1    -1    -1
     1     1     1     0     0     0     0     0     0
     1     1     1     0     0     0     0     0     0
     1     1     1     0     0     0     0     0     0
     1     1     1     0     0     0     0     0     0

However, I am looking for a better approach without using loops.

Upvotes: 5

Views: 945

Answers (1)

rayryeng
rayryeng

Reputation: 104464

This can be done purely by indexing. First declare your output matrix C as you did before, then replace the first two rows of C with A, then replace the first three columns of C with B:

%// Your code
A=zeros(2,9)-1;
B=ones(6,3);
C=zeros(max(size(A,1),size(B,1)),max(size(A,2),size(B,2)));

%// New code
C(1:size(A,1),:) = A;
C(:,1:size(B,2)) = B;

We get:

>> C

C =

     1     1     1    -1    -1    -1    -1    -1    -1
     1     1     1    -1    -1    -1    -1    -1    -1
     1     1     1     0     0     0     0     0     0
     1     1     1     0     0     0     0     0     0
     1     1     1     0     0     0     0     0     0
     1     1     1     0     0     0     0     0     0

Upvotes: 5

Related Questions