0
votes

I'm trying to practice curve fitting on a 2D Gaussian, but in order to do that I need to add random noise to my predefined Gaussian. My first instinct was to cycle through two for loops and create two matrices X and Y with random numbers, but when I tried that (I don't have the code anymore) Matlab wouldn't let me plot the Gaussian because I didn't generate my X and Y values using the meshgrid function. Since I seem to need to use meshgrid, can anyone help me figure out how to generate a random meshgrid so I can add some noise to my Gaussian?

amp = 1;
x0 = 0;
y0 = 0;
sigmaX = 1;
sigmaY = 1;
%X = 1:1:100;
%Y = 1:1:100;
[X,Y] = meshgrid(-3:.1:3);
%Z = X .* exp(-X.^2 - Y.^2);
Z = amp*exp(-((X-x0).^2/(2*sigmaX^2)+(Y-y0).^2/(2*sigmaY^2)));
surf(X, Y, Z);

%Add noise now

EDIT: So I found out that rand can return a random matrix which will work with the surf function (for some reason it wasn't working for me earlier though). The result looks something like this: noisy 2D gaussian

amp = 1;
x0 = 0;
y0 = 0;
sigmaX = 1;
sigmaY = 1;
[X,Y] = meshgrid(-3:.1:3);
%Z = X .* exp(-X.^2 - Y.^2);
Z = amp*exp(-((X-x0).^2/(2*sigmaX^2)+(Y-y0).^2/(2*sigmaY^2)));
surf(X, Y, Z);

%Make some noise
[xRows, xColumns] = size(X);
[yRows, yColumns] = size(Y);

figure(2)
X =  -.1 + (.1+.1)*rand(61,61);
Y =  -.1 + (.1+.1)*rand(61,61);
Z = amp*exp(-((X-x0).^2/(2*sigmaX^2)+(Y-y0).^2/(2*sigmaY^2)));
surf(X, Y, Z)

But I feel like the Gaussian has largely lost it's typical bell shape and looks more like a slope field than anything. I'm going to try and refine it but I would love any input.

2
There is no such thing as a random meshgrid in MATLAB. What you probably want to do is use the regular X Y values produced by meshgrid and instead add noise to the Z data you generate. Take a look at rand and randn to get started. - mikkola

2 Answers

1
votes

That's what i would do.

amp=1;
x0=0;
y0=0;
sigmaX=1;
sigmaY=1;
noiseAmp=.1;
x=[-2:.1:2];
y=[-2:.1:2];

%Create two Noise Vectors
noisez1=noiseAmp.*rand(1,length(x));
noisez2=noiseAmp.*rand(1,length(x));
% Make an meshgrid out of the two Vectors
[noiseZ1,noiseZ2]=meshgrid(noisez1,noisez2);
% Add the Meshgrids togehter
Noise=noiseZ1+noiseZ2;

[X,Y]=meshgrid(x,y);
% Add the Noise to the result of Z
Z=amp*exp(-((X-x0).^2/(2*sigmaX^2)+(Y-y0).^2/(2*sigmaY^2)))+Noise;
surf(X,Y,Z);
0
votes

if you just want a 2D plot you can try this

  amp=1;
  noiseAmp=0.01;
  x0=0;
  y0=0;
  sigmaX=1;
  sigmaY=1;
  x=[-5:.01:5];
  noiseY=noiseAmp*rand(1,length(x));
  y=noiseY+amp*exp(-((x-x0).^2/(2*sigmaX^2)));
  plot(x,y);

where noiseAmp is the Amplitude of the noise.

But if you still want to create a 3D plot with the surf() function, you have to add a random meshgrid to the Z result.