0
votes

I have following matrices :

X=1 2 3    

A=1 2 3  
  4 5 6  
  7 8 9  

I Want to do

for each (i,j) in A  
  B(i,j) = sum(A(i,j)*x)

i.e. each element of A is multiplied by vector X, and we sum all 3 elements of that vector.
Can it be done without for loop ?

2
Isn't that the same as multiplying A by the sum of X? - groovingandi
@grooveingandi Sorry, I mistakenly asked simpler version of my problem :). I have edited my question now. - Happy Mittal
Could you please roll back your edit and ask a new question? This way, @HighPerformanceMark's clever answer still makes sense, and we can tackle the new question with new answers. - Jonas

2 Answers

6
votes

Something like this perhaps ?

B = A.*sum(X)
1
votes

EDIT As @HighPerformanceMark points out, you can simply multiply by the sum of X, which is clearly preferrable. Below is a solution that does exactly the steps you wanted to do, which may make my solution useful for non-linear variants of the problem.

You can turn X into a 1-by-1-by-3 array, and multiply it with A to get a 3-by-3-by-3 array, which you can then sum along the third dimension:

X = permute(X,[1,3,2]); %# make X 1*1*3

B = sum( bsxfun(@times, A, X), 3); %# multiply and sum