# workaround for handling a large number of variables in the objective function of lsqnonlin

3 views (last 30 days)
Abdelwahab Afifi on 12 May 2020
Commented: Abdelwahab Afifi on 12 May 2020
I want to optimize my objective function
w0=zeros(m,1)
[w,resnorm] = lsqnonlin(@myfun,w0)
How can I dynamically define weights w(1) w(2) w(3) in my function to adapt any possible change in number of variables (m) as follow
function F = myfun(w)
global X % regression matrix of (nxm)
global Y % output vector (nx1)
F = Y - ( w(1)*X(:,1) + w(2)*X(:,2) + w(3)*X(:,3) + .. + w(m)*X(:,m) );
end
Stephen Cobeldick on 12 May 2020
Note that the global variables should be replaced by function parameterization:

Stephen Cobeldick on 12 May 2020
Edited: Stephen Cobeldick on 12 May 2020
>> X = rand(7,3);
>> w = rand(3,1);
>> w(1)*X(:,1) + w(2)*X(:,2) + w(3)*X(:,3) % what you do now
ans =
0.63892
0.43089
0.59637
0.89806
1.08999
0.98472
0.38443
>> X*w(:) % what you should do: matrix multiply
ans =
0.63892
0.43089
0.59637
0.89806
1.08999
0.98472
0.38443
Abdelwahab Afifi on 12 May 2020
I tried it and it works. many thanks

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by