Shinta Dwi
Shinta Dwi

Reputation: 71

How to merge two matrix into one matrix respectively based on the columns number Matlab

Example I have

A =[1 2;
    3 4]

B =[5 6;
    7 8]

I want the result is like this

C =[1 5 2 6;
    3 7 4 8]

Upvotes: 0

Views: 59

Answers (2)

Depends on the use, but with this particular example, you can make it like this:

C= [A, B];

and then:

C1=[C(:,1),C(:,3),C(:,2),C(:,4)]

C1 =

     1     5     2     6
     3     7     4     8

Upvotes: 1

Divakar
Divakar

Reputation: 221684

You can concatenate vertically and then reshape -

C = reshape([A;B],size(A,1),[])

Sample run -

>> A
A =
     1     2
     3     4
>> B
B =
     5     6
     7     8
>> reshape([A;B],size(A,1),[])
ans =
     1     5     2     6
     3     7     4     8

Upvotes: 4

Related Questions