Matlab coding help

1k Views Asked by At

I need to graph the following functions on MATLAB:

$$x(t)=\frac{3sin(2t)}{2}\\ y(t)=\frac{-4e^{-1/2t} sin(\frac{\sqrt{15}}{2}t)}{√15}+2e^{-1t/2}cos⁡(\frac{\sqrt{15t}}{2})\\ h(t)=x(t)+y(t)$$

I have the data points for this functions. I need help making a smooth curve on MATLAB.

I try this code and I get and error:

>> x=@(t)(3/2)*sin(2*t);
>> y=@(t)(1/sqrt(15))*exp(-0.5*t)*sin(sqrt(15)*0.5*t)+2*exp(-0.5*t)*cos(sqrt(15)*0.5*t);
>> g=@(t)x(t)+y(t);
>> t=0:0.1:20;
>> plot(t,x(t),y(t),g(t))
2

There are 2 best solutions below

13
On BEST ANSWER

One of the nicest ways to handle explicit functions in MATLAB is with anonymous functions. Using the syntax x = @(t)(...), you can replace the ... with function code, and then simply call x(t) whenever you want your function evaluated.

So, what you can do for your functions is

x = @(t)3/2*sin(2*t);
y = @(t)(-4/sqrt(15)*exp(-1/2*t).*sin(sqrt(15)/2*t)+2*exp(-1/2*t)).*cos(sqrt(15)/2*t);
h = @(t)x(t)+y(t);

Note that in the definition of y, I used the .* operator. This is an element-wise vector multiplication operation, so [a b].*[c d] returns [a*b c*d].

Then, you can specify your t-vector in any number of ways, say by using t = 0:.01:20, and then you can simply call plot(t,h(t)).


Why do I like anonymous functions so much?

  1. You can specify your functions up-front, without having to specify your domain first.
  2. You don't have to worry about row vs. column vectors. Whatever you put in as the argument is what you'll get out.
  3. They greatly simplify your code and code structure. Calling plot(t,h(t)) is unambiguous that $h$ is a function of $t$. By contrast, plot(t,h) or plot(t,x+y) doesn't give any indication as to the characteristics of the plot. Is it a function? A phase plane? A distribution?
0
On

Several ways of doing this. Easiest would be to define a vector $t$ from say, $[0,\pi]$ (e.g. t = linspace(0,pi,100) for 100 uniformly spaced points between $0$ and $\pi$).

Then create vectors x and y separately. For e.g. x = 1.5*sin(2*t). Use functions sqrt, exp, sin and cos to create the vector y. Don't forget to use .* when multiplying two vectors together component-wise (e.g. exp(-0.5*t).*sin(0.5*sqrt(15)*t)).

Then, plot it with:

plot(t,x+y)