Search code examples
matlabmatrixsumweighted

Weighted sum of elements in matrix - Matlab?


I have two 50 x 6 matrices, say A and B. I want to assign weights to each element of columns in matrix - more weight to elements occurring earlier in a column and less weight to elements occurring later in the same column...likewise for all 6 columns. Something like this:

cumsum(weight(row)*(A(row,col)-B(row,col)); % cumsum is for cumulative sum of matrix

How can we do it efficiently without using loops?


Solution

  • If you have your weight vector w as a 50x1 vector, then you can rewrite your code as

    cumsum(repmat(w,1,6).*(A-B))
    

    BTW, I don't know why you have the cumsum operating on a scalar in a loop... it has no effect. I'm assuming that you meant that's what you wanted to do with the entire matrix. Calling cumsum on a matrix will operate along each column by default. If you need to operate along the rows, you should call it with the optional dimension argument as cumsum(x,2), where x is whatever matrix you have.