MATLAB Answers

# Fitting a 3D gaussian to a 3D matrix

102 views (last 30 days)
Yatish Yatish on 8 Feb 2021
Edited: Matt J on 10 Feb 2021
I have a 3D matrix that I need to fit with a 3D gaussian function:
I need to get A, and all three σ's as the output after fitting.
I have tried to do it using Least Square fitting as:
[xx,yy,zz]=meshgrid(x,y,z);
Mat(:,:,:,1)=xx;Mat(:,:,:,2)=yy;Mat(:,:,:,3)=zz;
F=@(param,Mat) param(1)*exp(-(Mat(:,:,:,1).^2/(param(2))^2+Mat(:,:,:,2).^2/(param(3))^2+Mat(:,:,:,3).^2/(param(4))^2));
param0=[80000,10,10,10]; % initial parameters
param=lsqcurvefit(F,param0,Mat,D); % D is the 3D matrix that needs to be fit.
But, I get various errors. I don't think my approach is correct. Is there any other way?
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (2)

Are Mjaavatten on 8 Feb 2021
meshgrid arranges the xx and yy output matrices to fit the convention where the surface plots have x on the horizontal axis and y on the vertical, while you want to have x vary in the vertical direction in your matrices.
[yy,xx,zz]=meshgrid(y,x,z);
should fix the problem.
##### 5 CommentsShowHide 4 older comments
Yatish Yatish on 10 Feb 2021
The problem was with the matrix that I had attached. It works perfectly for the right 3D data. Thanks a lot for your help! :-)

Sign in to comment.

Matt J on 10 Feb 2021
Edited: Matt J on 10 Feb 2021
You can also use gaussfitn,
[xx,yy,zz]=meshgrid(x,y,z);
lbCell={0,[],[], zeros(3)};
ubCell={0,[],[], +diag(inf(1,3))}
param0={0,80000,[0,0,0], (1/10)*eye(3) };
param = gaussfitn([xx(:),yy(:),zz(:)], D(:),param0, lbCell, ubCell)
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!