0

A1 and A2 are two arrays of integers with the same dimensions 6000x2000.

I want to find a third matrix B by following these steps:

for i=1:1:6000
    for j=1:2000

        a1 = fliplr(dec2binvec(A1(i,j),14));  % Convert A1(i,j) to a binary vector
        a2 = fliplr(dec2binvec(A2(i,j),32));  % Convert A2(i,j) to a binary vector

        b = [a1 a2];

        B(i,j) = sum(b.*2.^(numel(b)-1:-1:0));  % Convert b to decimal


    end
end

my problem is the computation time to find B.

Is there a way to avoid loops in order to reduce the computation time ?

Example:

A1 = [2 3           A2 = [7 6
      4 5]                2 9]

A1(1,1) = 2 and A2(1,1) = 7

a1 = [0 0 0 1 0] (eg 5 bits) a2 = [0 0 0 1 1 1] (eg 6 bits)

b = [a1 a2] = [0 0 0 1 0 0 0 0 1 1 1]

B1(1,1) = sum(b.*2.^(numel(b)-1:-1:0)) = 135
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
bzak
  • 563
  • 1
  • 8
  • 21
  • 1
    Please post a small numeric example (say with 2x2 matrices), to clarify endianness etc – Luis Mendo Feb 19 '15 at 22:21
  • 1
    `dec2binvec` returns least significant bit first, but `b.*2.^(numel(b)-1:-1:0)` uses it as highest significant bit first. Did you verify you really get what you want with this code? – Daniel Feb 19 '15 at 22:30
  • @LuisMendo : I added an example. – bzak Feb 19 '15 at 22:33
  • @bzak: The example and your code don't match, your code flips the bits. – Daniel Feb 19 '15 at 22:36
  • @Daniel: I think I made a mistake with dec2binvec! – bzak Feb 19 '15 at 22:37
  • @Daniel: is there a function that returns highest significant bit first? – bzak Feb 19 '15 at 22:42
  • 1
    @bzak: Matlab always uses lowest significant bit first for logical vectors and highest significant bit first for string representations. If you need something else, use `fliplr(dec2binvec(2,6))`. – Daniel Feb 19 '15 at 22:46

3 Answers3

4

Using your example:

A1 = [2 3;           
      4 5];            
A2 = [7 6;
      2 9];
B=bitshift(A1,6)+A2

Output:

B =

   135   198
   258   329
beaker
  • 16,331
  • 3
  • 32
  • 49
1

If I understand your example correctly, you only need to bit-shift A1 (i.e. multiply by a power of 2):

M = 5; %// not used actually
N = 6;
B = A1 * 2^N + A2;

In your example, this gives

B =
   135   198
   258   329
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
1

I assume the example contains what you want. Simply use math ;)

A1 = [2 3;4,5]
A2=[7 6;2 9]
A1.*2^6+A2

Please be aware that doubles can hold up to 53 bits without precision loss. Recent versions of matlab support uint64. For even longer numbers check vpa, but vpa will result in slow code.

Daniel
  • 36,610
  • 3
  • 36
  • 69
  • 1
    http://stackoverflow.com/questions/1848700/biggest-integer-that-can-be-stored-in-a-double – bzak Mar 02 '15 at 15:44