naman
naman

Reputation: 35

MATLAB: How to concatenate two numeric matrices such that the corresponding numbers in each matrix are now concatenated

For example lets take matrices:

A= 1 0 0
   0 1 0
   1 1 0

B= 1 1 0
   0 0 1
   1 0 0

The required result is

AB=11 01 00
   00 10 01
   11 10 00

Upvotes: 1

Views: 61

Answers (2)

Dan
Dan

Reputation: 45741

Try this:

reshape(mat2cell(dec2bin(A+B), ones(numel(A),1)), size(A))

Or a more compact suggestion from Rody:

reshape(num2cell(dec2bin(A+B), 2), size(A))

Upvotes: 3

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

3 ways pop in mind; it depends a bit on what you want exactly.

% Example data (make them logical to save space)
A= [1 0 0
    0 1 0
    1 1 0] == 1;

B= [1 1 0
    0 0 1
    1 0 0] == 1;

%# Method 1
cols = size(A,2) + size(B,2);
C1(:, 1:2:cols) = A;
C1(:, 2:2:cols) = B


%# Method 2
C2 = cellfun(@horzcat, num2cell(A),num2cell(B), 'UniformOutput',false)
C2{:,1}

%# Method 3 (same as 2, really, but simpler)
C3 = strcat(num2cell(A), num2cell(B))
C3{:,1}

Upvotes: 2

Related Questions