plotting a function in MATLAB

63 Views Asked by At

I have an assignment i'm working on and I need to plot the following:

$$f(x,y)= \cos(3x)+2\sin(y+4x)$$

I always define $x$ as in the range and assign $y$ to be the function. but since it's a function of two variables I have no idea what to assign $y$ to? please help

1

There are 1 best solutions below

6
On BEST ANSWER

Your problem is that you want to define $y$ as a function of $x$ which is not at all the point here. What is asked to you is to represent not a curve but a surface with "height" $z$ at the vertical position of point $(x,y)$ computed by the given formula. Here is a Matlab program for that :

clear all;close all ; %as always
[X,Y] = meshgrid(0:0.05:3*pi); % (explanation below) 
Z = cos(3*X)+2*sin(Y+4*X);
s = surf(X,Y,Z); 
view([-5,45]); % angles of view
set(s,'edgecolor','none'); % elimination of hideous separation lines 

If you want a contour map (level lines), just replace "surf" by "contour", producing "standard" contour lines. enter image description here

Fig. 1 : Nice "silky" effect, isn't it ?


Sometimes, "meshgrid" is misunderstood.

First of all, in the above program, we could have used it like this :

[X,Y]=meshgrid(0:0.05:4*pi,0:0.05:2*pi), yielding a rectangular space of representation, instead of a square one.

Now for the understanding of what $X$ and $Y$ really are, let us take a very simple example :

Consider instruction : [X,Y]=meshgrid([3,4],[7,8,9]) which gives :

$$X=\begin{matrix} 3 & 4 \\ 3 & 4\\ 3 & 4 \end{matrix} , \ \ \ Y=\begin{matrix} 7 & 7\\ 8 & 8\\ 9 & 9\end{matrix}$$

When the two above arrays are "grouped", you get :

$$\begin{matrix} (3,7) & (4,7) \\ (3,8) & (4,8)\\ (3,9) & (4,9) \end{matrix} $$

which is plainly the cartesian product $[3,4] \times [7,8,9]$.

That's what $X$ and $Y$ really are.