Reputation: 1
How do I write an expression in Matlab code involving summation of a variable and then how do I minimize the expression? ex. I need to minimize the following function
E= \sum_{i,j}[C_{ij}(r_{ij}) + C2_{ij}(r_{ij})^2]
I need to minimize the above expression for any values of r_{ij}s where i and j vary.
I could use the fmincon() in MATLAB but I am unable to write my expression suitably to give it as input to the fmincon().
Thanks.
Upvotes: 0
Views: 1943
Reputation: 4787
fmincon
and other optimization functions do not require you to write everything as an expression, they can optimize for functions as well.
function E = criterion(r, C, C2)
e = C.*r + C2.*r.^2;
E = sum(e(:));
I'm not completely sure about the syntax required by fmincon
, but I guess it's something like E = f(theta)
, where theta
is a parameter vector you want adjusted such that E
is minimal. Since I don't find your problem clearly described, I will assume your parameters are C
and C2
(in the case that r
are your parameters, the case is similar and simpler).
As fmincon
uses a vector to store the coefficients, we need a function that takes such a vector and transforms it into the sizes required by the criterion
function above.
function E = criterionRolledC(theta,r)
assert(numel(theta)==2*numel(r), 'The size of theta has to be twice the size of r');
[M N] = size(r);
C = theta(1:M*N);
C2 = theta(M*N+1:end);
C = reshape(C , M, N);
C2 = reshape(C2, M, N);
E = criterion(r,C,C2);
That way, you can make an anonymous function that easily conforms to the interface of the optimizer: @(theta)(criterionRolledC(theta,rValues))
will do when the variable rValues
in your current workspace contains your r
values.
In case you want the exact opposite, i.e. your parameters are r
, it is simpler:
function E = criterionRolledR(theta,C,C2)
assert(numel(theta)==numel(C), 'The size of theta has to be the same size as C');
assert(all(size(C)==size(C2)), 'C and C2 need to have the same size');
[M N] = size(C);
r = reshape(theta, M, N);
E = criterion(r,C,C2);
And you can construct an anonymous function similarly to the other case.
Upvotes: 1
Reputation: 8269
Try this:
E = sum(sum( C.*r + C2.*r.^2 ));
where C
, C2
and r
are matrices of the same shape.
Upvotes: 1