How to generate plot of a function?

조회 수: 2 (최근 30일)
amateurintraining
amateurintraining 2017년 9월 29일
댓글: OCDER 2017년 10월 1일
I have the code:
function [ z ] = fun( )
%FUN Produces 3D surface plot with contours below the surface of f(x)
dx=0.1*pi;
x=linspace(0,nx*dx,nx);
y=linspace(0,nx*dx,nx);
wave1=makewave([1,0],sin);
wave2=makewave([0,1],cos);
wave3=makewave([200,20],sin);
wave4=makewave([1,1],sin);
z=wave1+wave2+wave3+wave4;
surfc(x,y,z);
title('Some Waves')
xlabel(x)
ylabel(y)
zlabel('amplitude')
end
function [ wave ] = makewave( coefs, wavefun )
wave=wavefun(coefs(1)*x+coefs(2)*y);
end
That should produce a 3D surface plot of f(x)=sin(x)+cos(y)+sin(20y)+sin(x+y)
And:
When nx=100
How do I define nx if nx is also an input?

채택된 답변

OCDER
OCDER 2017년 9월 29일
편집: OCDER 2017년 9월 29일
It was almost right, but a few things needed some changes. See comments in the code. To run this on the command line:
>> nx = 100; %nx defined OUTSIDE the function is a different variable than the nx inside fun.
>> z = fun(nx);
Here is the edited function that should get you what you want now:
function [ z ] = fun(nx) %specify input to fun as nx
%FUN Produces 3D surface plot with contours below the surface of f(x)
dx=0.1*pi;
x=linspace(0,nx*dx,nx);
y=linspace(0,nx*dx,nx);
[X, Y] = meshgrid(x, y); %You need a 2D matrix to use surfc.
wave1=makewave(X, Y, [1,0], @sin); %To pass a function, use function handle @sin
wave2=makewave(X, Y, [0,1], @cos);
wave3=makewave(X, Y, [200,20], @sin);
wave4=makewave(X, Y, [1,1], @sin);
z=wave1+wave2+wave3+wave4;
surfc(x,y,z);
title('Some Waves')
xlabel('x') %must be a string, 'x'
ylabel('y') %must be a string, 'y'
zlabel('amplitude')
end
function [ wave ] = makewave(X, Y, coefs, wavefun) %you need to pass X and Y as inputs too.
wave=wavefun(coefs(1)*X+coefs(2)*Y);
end
  댓글 수: 2
amateurintraining
amateurintraining 2017년 10월 1일
Thank you so much!
OCDER
OCDER 2017년 10월 1일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Contour Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by