How to generate plot of a function?

2 次查看(过去 30 天)
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by