NumenorForLife
NumenorForLife

Reputation: 1746

Vectorizing the Sum of a Triple For Loop

Currently, I am trying to build the matrix Alpha through this triple-loop:

Alpha = zeros(a_length, b_length);   
for a = 1:a_length
  for b = 1:b_length
      for c = 1:c_length
          Alpha(a,b) = Alpha(a,b) + Beta(c,a) * Gamma(b,c);
      end
  end
end

Is there a way to pass in two vectors to the Beta and Gamma Matrices, such that I can construct the entirety of Alpha in a single, vectorized line of elegant code?

Upvotes: 1

Views: 279

Answers (1)

Divakar
Divakar

Reputation: 221554

You could use simple matrix multiplication to your rescue -

Alpha = (Gamma*Beta).'

Or this way -

Alpha = Beta.'*Gamma.'

Or a bit complicated bsxfun based approach -

Alpha = sum(bsxfun(@times,permute(Gamma,[3 1 2]),permute(Beta,[2 3 1])),3)

And if you want to avoid one permute from the earlier bsxfun approach -

Alpha = squeeze(sum(bsxfun(@times,Gamma,permute(Beta,[3 1 2])),2)).'

Or this -

Alpha = squeeze(sum(bsxfun(@times,Beta.',permute(Gamma,[3 2 1])),2))

Upvotes: 4

Related Questions