Building matrices using column vector and matrix in matlab

Viewed 156

I have a column vector A (6x1) with values [6 3 10 4 2 8]'; and a matrix B (6x5) with values

B = [1  2  3  0  4 ; 
     3  7  8  5  0 ; 
     0  9  1  0  1 ; 
     5  0  3  1  2 ;    
     4  6  7  6  4 ; 
     3  1  2  7  3]

I want to make five matrices with size 6x2 using Matlab.

  • The first column is vector A

  • The second column is columns from B, like [A, B(first col)], [A, B(second col)]

    1. First matrix is [6 1; 3 3; 10 0; 4 5; 2 4; 8 3];
    2. 2nd matrix is [6 2; 3 7; 10 9; 4 0; 2 6; 8 1]
    3. ... and so on

Any help I really appreciate it

3 Answers

You could use a loop

C = NaN( size(B,1), 2, size(B,2) );
for ii = 1:size(B,2)
    C(:,:,ii) = [A, B(:,ii)];
end

This gives you a 3D array, where each slice in the 3rd dimension is a 6x2 matrix (for this example) as desired. You would access the nth slice with C(:,:,n).

You can do this slightly more concisely with arrayfun, but it's basically a loop in disguise

C = arrayfun( @(ii) [A, B(:,ii)], 1:size(B,2), 'uni', 0 );
C = cat(3, C{:} );

You could omit the cat function if you're happy with results in a cell array, where you access the nth matrix with C{n}.

You could first make a copy of the columns of A, then concatenate A and B, and reshape:

At = repmat(A, 1, size(B,2));
C = reshape([At;B], 6, 2, []);

Or oneliner:

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

Then retrieve your matrices with C(:,:,k)

you can use this 
  1. first_matrix=[A,B(:,1)];
  2. second_matrix=[A,B(:,2)];
  3. third_matrix=[A,B(:,3)];
  4. ... and so on
Related