Search code examples
matlabmatrixmultiplicationcell-array

Multiplying Cell with elements of a matrix Matlab


I have a 1xm cell array A{}, with each element of the array being NxN matrix and a matrix W(N1,m).
I need to calculate

Sum(j) = W(j,1)*A{1,1} + W(j,2)*A{1,2}  

and I am doing the following:

for j=1:N1
  sum=false(N);  
  for k=1:m  
    sum = sum + W(j,k)*A{1,k};  
  end  
  Sum(j)=sum  
end

Or more visually :
Matrix W(let's say N1=2)
|W11 W12||A{1,1}| = |W11*A{1,1} + W12*A{1,2}|
|W21 W22||A{1,2}| = |W21*A{1,1} + W22*A{1,2}|

Is there a way of doing it without using the loops?


Solution

  • To do that without for-loops, you can rape (pardon the expression) the arrayfun command:

    w_func = @(j)arrayfun(@(k)(W(j, k) * A{k}), 1:m, 'Un', 0)
    sum_func = @(x)sum(cat(3, x{:}), 3)
    S = arrayfun(@(j)sum_func(w_func(j)), 1:N1, 'Un', 0);
    

    This produces a cell array S that contains all the sums, from S{1} to S{N1}.