# lsqnonlin for 2 independent variables

15 views (last 30 days)
dhlee on 29 Aug 2021
Answered: Rik on 29 Aug 2021
I want to find 2 variables(x,y -> complex number) with lsqnonlin function.
For example, I have 2 equations and 2 variable DATA.
Please check and advise my code. Thank you~
<DATA>
S11=1+i;
S21=2+2i;
<EQUATION>
1) S11=x*y+i*(x+y)
2) S21=x*y-i*(x^2+y^2)
---------------------
clear all;
clc;
close all;
S11=1+i;
S21=2+2i;
x0=0.1+0.1i;
y0=0.2+0.2i;
F = @(x) myfun_lsq(x,y,S11,S21)
x=lsqnonlin(F,x0)
y=lsqnonlin(F,y0)
function F = myfun_lsq(x,y,S11,S21)
Fc1=x*y+i*(x*y)-S11;
Fc2=x*y-i*(x^2+y^2)-S21;
F = [Fc1, Fc2];
end

Rik on 29 Aug 2021
You should merge x and y to a single variable (i.e. a 2 element vector). That way you can do this with a single call to lsqnonlin.
And you should remove that clc, clear all, close all. You don't need it and using it is a clear indication you don't know what you want to happen. Are you opening any figures? Do you really want to reduce the performance of several functions by wiping the optimization from memory with clear all?