Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Vectorizing to remove a loop

Subject: Vectorizing to remove a loop

From: Michael

Date: 30 Jul, 2014 00:59:12

Message: 1 of 2

How can I vectorize this loop out of existence?

To set up my problem as generally as possible, A and B are matrices that have the same number of rows, say m. Otherwise they have arbitrary column size.

Let size(A, 2) = k, and size(B, 2) = l

The loop I want to vectorize.

 for t = 1:m
    ARP = ARP + A(t,:)' * B(t,:)
 end
Which is a sum of matrices size (kX1)X(1Xl) = kXl.

Finally ARP = 1/m * ARP

After some research I built this 'solution' which balloons up the size of my matrices and in fact fails when the matrices get largish.

%Create copies of A stacked on top of each other to a depth of l
exA = repmat(A, l, 1); % (m * k)Xl

%Reshape it so that exA has each column of A cloned k times
exA = reshape(exA, m, k * l); % mX(k * l)

%Create copies of B stacked next to each other to a width k
exB = repmat(B, 1, k); % mX(l * k)

%Both matrices are now m X k*l so we can element-wise multiply
%and take the mean of the rows.


ARP = mean(exA .* exB, 1); % 1X(k * l)

ARP = reshape(ARP, l, k)';

I am also aware that repmat can be replaced in vectorizations with bsxfun, although it is not clear how to implement bsxfun in this case. I appreciate any help that gets me to an optimized solution and also illustrates techniques for vectorization that I can study for similar problems.

Thanks in advance Mike

Subject: Vectorizing to remove a loop

From: Roger Stafford

Date: 30 Jul, 2014 01:51:11

Message: 2 of 2

"Michael" wrote in message <lr9g10$htf$1@newscl01ah.mathworks.com>...
> How can I vectorize this loop out of existence?
>
> To set up my problem as generally as possible, A and B are matrices that have the same number of rows, say m. Otherwise they have arbitrary column size.
>
> Let size(A, 2) = k, and size(B, 2) = l
>
> The loop I want to vectorize.
>
> for t = 1:m
> ARP = ARP + A(t,:)' * B(t,:)
> end
> Which is a sum of matrices size (kX1)X(1Xl) = kXl.
>
> Finally ARP = 1/m * ARP
- - - - - - - - - -
You have exactly described matrix multiplication. Your vectorized version would be nothing but:

 1/m*A'*B

Roger Stafford

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us