Oscar
Oscar

Reputation: 241

Matlab, sum of symbolic fucntions

I'm trying to implement the following function in matlab where all variables except "o" are known. And then when the function is defined find the min based on an initial guess using the lsqnonlin method. enter image description here

Matlab code:

%%
x0 = 23;
[x,resnorm] = lsqnonlin(@myfun,x0);

%%

function F = myfun(x)
k = 1:5;
p = 1:5;
F = max_index_values_5(k,p)-(sqrt(a(k)-b(p))+x);
end

Where max_index_values is a 5*5 matrix, a and b are vectors of length 5 and u*v results in zero which is why it's not in the Matlab code. When i run the code I get the following error:

Undefined function 'max_index_values_5' for input arguments of type 'double'.

Can someone please help me implement the function so it works with lsqnonlin?

Upvotes: 0

Views: 57

Answers (1)

Anton
Anton

Reputation: 4684

Here is an example of using two different solvers (at first I did not have access to the Optimization Toolbox and used the available fminsearch)

function [] = main()

    z = [1 2 3;
         4 5 6;
         7 8 9];

    a = [1;3;5];

    b = [1;7;2];

    opt_fms = optimset('Display','iter');

    x0 = 1;
    %[x, fval] = fminsearch(@myfun,x0, opt_fms, z, a, b)
    [x, fval] = lsqnonlin(@myfun,x0, [], [], opt_fms, z, a, b)
end

function F = myfun(o, z, a, b)
    F = 0;
    n = numel(a);
    for i = 1:n
        for j = 1:n
            F = F + (z(i, j) - (sqrt(a(i, 1)+b(j, 1)) + o)).^2;
        end
    end
end

lsqnonlin result (the function return value in power of 2):

x =
    2.5631
fval =
   2.1663e+03

fminsearch result:

x =
    2.5631
fval =
   46.5441

Here is the function's plot with the optimization result (from fminsearch):

enter image description here

Upvotes: 0

Related Questions