How to generate plot of a function?

1 view (last 30 days)
amateurintraining
amateurintraining on 29 Sep 2017
Commented: OCDER on 1 Oct 2017
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?

Accepted Answer

OCDER
OCDER on 29 Sep 2017
Edited: OCDER on 29 Sep 2017
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

More Answers (0)

Categories

Find more on Contour Plots in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!