# plotting a function with mesh

6 views (last 30 days)
Artur Walter on 17 Oct 2019
Hallo
I want to plot a function with mesh and find it's minimum
clear; close; clc;
f = @(x)(x(1).^2 + x(2).^2);
N = 200;
x1 = 0:2/(N-1):2;
x2 = -2:4/(N-1):2;
[x1, x2]= meshgrid(x1, x2);
x3 = f(x1, x2);
mesh (x1, x2, x3)
z = fminsearch(g , [0.5, 0.5])
% or I tried
function z = f(x1, x2)
z = x1.^2 + x2.^2;
end
function z = g(x)
z = x(1).^2 + x(2).^2;
end
Everthing failed!
How can I do it?

Adam Danz on 17 Oct 2019
"Everthing failed!"
This doesn't tell us what the problem is. If you're getting an error message, provide the entire copy-pasted message. If you're not getting an error but the plot isn't as expected, provide more detail about that.
Adam Danz on 17 Oct 2019
For starters, you've got a local function named f and an anonymous function named f. You can't have both in the same script.

Swastik Sanjay Chaudhury on 4 Dec 2019
Hello Artur, I agree with the comment as mentioned by Adam Danz. A basic modification maked the code work without any problem.
clear; close; clc;
t = @(x)(x(1).^2 + x(2).^2);
N = 200;
x1 = 0:2/(N-1):2;
x2 = -2:4/(N-1):2;
[x1, x2]= meshgrid(x1, x2);
x3 = f(x1, x2);
mesh (x1, x2, x3)
z = fminsearch(t , [0.5, 0.5])
% or I tried
function z = f(x1, x2)
z = x1.^2 + x2.^2;
end

R2019a

### Community Treasure Hunt

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

Start Hunting!