Plotting 3D Graph with MATLAB Function

Click For Summary
SUMMARY

The discussion focuses on creating a 3D graph in MATLAB using a function that accepts parameters, specifically an equation like sin(x) - cos(y). The user encountered an error when attempting to plot the graph due to the incorrect assignment of the variable z. The solution involves modifying the function to evaluate z as z = f(x,y) and calling the function with a function handle, such as graph(@(x,y) cos(x) - sin(y)). This ensures that z is computed as a matrix suitable for the surf function.

PREREQUISITES
  • Familiarity with MATLAB programming
  • Understanding of function handles in MATLAB
  • Knowledge of meshgrid function for 3D plotting
  • Basic concepts of 3D surface plotting using surf function
NEXT STEPS
  • Explore MATLAB function handles in detail
  • Learn about the meshgrid function and its applications in 3D plotting
  • Investigate the surf function and its parameters for surface plotting
  • Practice creating custom functions for various mathematical equations in MATLAB
USEFUL FOR

This discussion is beneficial for MATLAB users, particularly those interested in 3D data visualization, mathematical modeling, and anyone looking to enhance their skills in function handling and surface plotting in MATLAB.

stihl29
Messages
24
Reaction score
0
Hi, i need to pass a function in MATLAB a few parameters, one of the parameters is an equation such as :
sin(x)-cos(y)
and have it make the 3d graph, i have no problem setting up the meshgrid etc and getting it to work running strait from the m-file

function graph = graph(f)
n=20;
x = (-n:1:n);
y = (-n:1:n);
[x,y] = meshgrid(x,y);

z=f;

surf(x,y,z);

end

example of running the function

graph(sin(x)-cos(y))

right now when i run it i get.

? Error using ==> surf at 78
Z must be a matrix, not a scalar or vector.

Error in ==> graph at 7
surf(x,y,z);


Any advice would be great.
 
Physics news on Phys.org
Look up "help function pointer" and follow their examples.
 
Two things,

1) Change the line z = f to z = f(x,y)

2) When you call the function, use graph(@(x,y) cos(x) - sin(y))
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 1 ·
Replies
1
Views
4K