Star
Star

Reputation: 2299

Vectorising a code using xor in Matlab

I have an mxn array r in Matlab with elements that are zeros or ones.

I want to construct a vector p of dimension mxn such that for i=1,...,m

p(i,1)=r(i,1)

p(i,2)=r(i,2)XOR r(i,1)

p(i,3)=r(i,3) XOR r(i,2)

...

p(i,n)=r(i,n) XOR r(i,n-1)

This code does what I want but it is slow for m,n large. Could you suggest something faster?

m=4;
n=5;
r=[1 1 1 1 1; ...
   0 0 1 0 0; ...
   1 0 1 0 1; ...
   0 1 0 0 0];

p=zeros(m,n);

for i=1:m
    p(i,1)=r(i,1);
    for j=2:n
        p(i,j)=xor(r(i,j),r(i,j-1));
    end
end

Upvotes: 1

Views: 54

Answers (1)

Pursuit
Pursuit

Reputation: 12345

Sure:

p            = zeros(m,n);
p(:,1)       = r(:,1);
p(:,2:end)   = xor(  r(:,1:(end-1)),   r(:,2:n)   );

What we're doing here is:

  1. Pre-allocating the array. Same as your code.
  2. Fill in the first column of p with the first column of r
  3. Fill in the 2nd - last columns of p with the desired XOR operation. As inputs to the XOR we are using two large sections of r. The first is the 1st - (last-1)th columns. The second is the 2nd through last columns.

Upvotes: 2

Related Questions