2

Element by element, I want to concatenate binary values from different matrices to one matrix.

For example,

|1 0 0|  |0 1 0|   |10 01 00|         
|0 1 1|  |1 1 0| = |01 11 10|       
|1 0 1|  |0 0 1|   |10 00 11|

How can this be done?

Cecilia
  • 4,512
  • 3
  • 32
  • 75
Michael
  • 33
  • 7
  • 2
    As far as I know, Matlab doesn't have the ability enter numbers in numeric matrices using binary values. Matlab's logical matrix type only stores one bit binary, i.e. true and false. Your output matrix will either need to be numeric in which case it will be displayed in decimal or strings in which case you won't be able to use more math operations. – Cecilia May 12 '15 at 19:16
  • might help you: http://stackoverflow.com/questions/13347749/merge-two-binary-vectors – brodoll May 12 '15 at 19:18

2 Answers2

3

I would store the output matrix as a decimal matrix and convert to binary strings when accessing elements.

To concatenate the elements, treat each input matrix as a binary digit

A1 = [1 0 0; 0 1 1; 1 0 1];
A2 = [0 1 0; 1 1 0; 0 0 1];
output = A1 * 2^1 + A2 * 2^0;
output_str = arrayfun(@dec2bin, output, 'UniformOutput', false);  

output will be a double matrix

[2,  1,  0;
 1,  3,  2;
 2,  0,  3]

output_str will be a cell array of strings

['10', '1',  '0';
 '1',  '11', '10';
 '10', '0',  '11']
Cecilia
  • 4,512
  • 3
  • 32
  • 75
1

Here is one alternative without bin2dec or dec2bin conversion

out = arrayfun(@(x,y) strcat(num2str(x),num2str(y)),A1,A2,'Uni',0);

Input:

A1 = [1 0 0; 0 1 1; 1 0 1];
A2 = [0 1 0; 1 1 0; 0 0 1];

output:

>> out

out = 

'10'    '01'    '00'
'01'    '11'    '10'
'10'    '00'    '11'

If you want it as numeric instead of string, you might do this:

outp = cellfun(@(x) str2double(x), out);

output:

>> outp

outp =

10     1     0
 1    11    10
10     0    11
Santhan Salai
  • 3,888
  • 19
  • 29