How to plot using peaks function?
조회 수: 11 (최근 30일)
이전 댓글 표시
The Peaks function (peaks()) in MATLAB which is used for demonstrating graphic functions can be mathematically represented as shown below.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1377189/image.png)
- Create arrays for x and y axes according to the domain constraints
- Use meshgrid () to create 2D coordinate matrices for x and y axes
- Use nested for loop structure to access x and y coordinates for each point
- Create a function that evaluates and returns the value of f(x,y) for a each value of x and y
- 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.
댓글 수: 0
답변 (1개)
Dyuman Joshi
2023년 5월 8일
편집: Dyuman Joshi
2023년 5월 8일
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)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Line Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!