Filter löschen
Filter löschen

How to generate plot of a function?

1 Ansicht (letzte 30 Tage)
amateurintraining
amateurintraining am 29 Sep. 2017
Kommentiert: OCDER am 1 Okt. 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?

Akzeptierte Antwort

OCDER
OCDER am 29 Sep. 2017
Bearbeitet: OCDER am 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
  2 Kommentare
amateurintraining
amateurintraining am 1 Okt. 2017
Thank you so much!
OCDER
OCDER am 1 Okt. 2017
You're welcome!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by