# Leastsq function for z=f(x,y) problem

**URL:** <https://scilab.discourse.group/t/leastsq-function-for-z-f-x-y-problem/127>\
**Category:** Optimization\
**Created:** [August 3, 2023, 3:19pm UTC](https://scilab.discourse.group/t/leastsq-function-for-z-f-x-y-problem/127 "2023-08-03T15:19:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![QwillDune](https://yyz2.discourse-cdn.com/free1/user_avatar/scilab.discourse.group/qwilldune/32/152_2.png) [@QwillDune](https://scilab.discourse.group/u/QwillDune)\
**Post date:** [August 3, 2023, 3:19pm UTC](https://scilab.discourse.group/t/leastsq-function-for-z-f-x-y-problem/127/1 "2023-08-03T15:19:23Z")

</div>

Hello,  
Is it possible to use leastsq function on a 3D problem like z=f(x,y)?  
if yes, can anyone share an example?  
BR

* * *

My best guess so far

* * *

clc  
clear  
alvclose(winsid())

// Function definition  
function F=funct(sol,X,Y)  
F=1-exp(-(sol(1).\*Y+sol(2)).\*X.^2)+grand(size(Y,‘r’),size(Y,‘c’),“nor”,0,0.025)  
// added noise  
endfunction

// Function parameters  
tmax=3  
ao=4e-2  
bo=1e-2  
time=linspace(0,tmax,100)’  
temp=linspace(20,80,4)’  
[X,Y]=meshgrid(time,temp)  
Z=funct([ao bo],X,Y)

// plot the noisy data  
scatter3d(X,Y,Z,‘.’)  
gca().zoom\_box=[0 0 3 100 -0.2 1.2]

// Error definition  
function dist = Error(sol, X, Y, Z)  
dist = Z - funct(sol, X, Y);  
endfunction

eps=10\*%eps;  
level=1000  
p0 = [1 1]‘\*1e-2;  
[xopt, fopt, info] = leastsq(list(Error, X, Y, Z), p0’)//, [eps,eps,eps,level,eps,level]);

---

<div class="post-metadata">

**Author:** ![mottelet](https://yyz2.discourse-cdn.com/free1/user_avatar/scilab.discourse.group/mottelet/32/13_2.png) [@mottelet](https://scilab.discourse.group/u/mottelet)\
**Post date:** [August 4, 2023, 3:07pm UTC](https://scilab.discourse.group/t/leastsq-function-for-z-f-x-y-problem/127/2 "2023-08-04T15:07:52Z")

</div>

Hello,

You just have to reshape the residual matrix `dist`, i.e.

```auto
dist=dist(:)

```

so that `leastsq` sees a classical vector residual.

S.

---

<div class="post-metadata">

**Author:** ![QwillDune](https://yyz2.discourse-cdn.com/free1/user_avatar/scilab.discourse.group/qwilldune/32/152_2.png) [@QwillDune](https://scilab.discourse.group/u/QwillDune)\
**Post date:** [August 4, 2023, 5:44pm UTC](https://scilab.discourse.group/t/leastsq-function-for-z-f-x-y-problem/127/3 "2023-08-04T17:44:54Z")

</div>

Of course … I’m kidding … you remove a stone from my shoe  
Thank you  
F
