# How to plot using peaks function?

26 views (last 30 days)
Shailendra Shankar on 8 May 2023
Edited: Dyuman Joshi on 8 May 2023
The Peaks function (peaks()) in MATLAB which is used for demonstrating graphic functions can be mathematically represented as shown below. 1. Create arrays for x and y axes according to the domain constraints
2. Use meshgrid () to create 2D coordinate matrices for x and y axes
3. Use nested for loop structure to access x and y coordinates for each point
4. Create a function that evaluates and returns the value of f(x,y) for a each value of x and y
5. Create a Contour plot and a Surf plot with proper formatting, each in a separate figure window (use figure() command) and explain what you observe/understand from the plots.
Here is my code:
clear all
close all
clc
x=linspace(-3,3,10);
y=linspace(-3,3,10);
[X,Y]= meshgrid(x,y);
ct=-3
for i=1:length(X)
for j=1:length(Y)
input_vector(1)=X(i,j);
input_vector(2)=Y(i,j);
f(i,j)=peaks_ex(input_vector);
end
end
figure(1)
hold on
grid on
surf(X,Y,-f)
function[f] = peaks_ex(input_vector)
x = input_vector(1);
y = input_vector(2);
f=peaks(x,y)
end
I know there is plenty wrong here can any one help me out here.
Thank you.

Dyuman Joshi on 8 May 2023
Edited: Dyuman Joshi on 8 May 2023
You are asked to create a function to evaluate the value at each point pair individually rather than use the peaks() function and evaluate the whole input directly.
Define a function handle using the formula given and store the result in another variable in every iteration of the nested loop. Your code will look like this -
x=linspace(-3,3,10);
y=linspace(-3,3,10);
[X,Y]= meshgrid(x,y);
%What is the use of ct?
ct=-3
%Define the function, I am leaving it to you.
fun = @(x,y) ...;
%pre-allocate output variable
Z = zeros(size(X));
for i=1:length(X)
for j=1:length(Y)
Z(i,j) = fun(X(i),Y(j))
end
end
figure(1)
hold on
grid on
surf(X,Y,Z)
figure(2)
hold on
grid on
contour(X,Y,Z)