Search code examples
matlabmathematical-optimization

Double Summation expression in MATLAB


I have a Parameter matrix, C of size 2x2. It looks like this.

C= [2 4; 6 8]

I have a decision variable, X of size 2x2. It looks like this

[ X('S1', 'D1')    X('S1', 'D2') ]
[ X('S2', 'D1')    X('S2', 'D2') ]

I want to formulate my Objective Function as a series of double expression (Please refer the attachment),

enter image description here

Which shall look like the following after the expansion.

Z = 2*X('S1', 'D1')  + 4*X('S1', 'D2') + 6*X('S2', 'D1')  + 8*X('S2', 'D2') 

I try the following.

Z = sum(C.*X,1);

But it creates An optimizationExpression of size 1x3, which is not desired.

What am I doing wrong? Is there any easier way to do so without using for loop. I have just started learning "Problem-Based Optimization" in MATLAB today. Any help will be greatly appreciated.


Solution

  • As C and X are 2x2 matrices, so C.*X gives a 2x2 matrix. With sum(C.*X,1);, summation is done along the first dimension (i.e. rows are added). But you want to sum all the elements. So if you convert your matrices into a vector and then multiply element-wise and then apply sum, it will add all the elements i.e.

    Z = sum(C(:).*X(:));
    

    Alternatively, you can first multiply and then convert the result into a vector before applying sum.

    CX = C.*X;
    Z = sum(CX(:));
    

    or sum along all the dimensions one by one. But I'd go with the solution suggested in the beginning.