MATLAB: Can’t plot exp * sin graph

expmatlab function

i can't plot this expression…. i dont know why. please help

Best Answer

Your problem lies in not understanding the difference between the .* and * operators. (In fact, this was probably why you were assigned this homework problem in the first place, to teach you about the need for the .* operator.)
MATLAB is a matrix language, designed to work with matrix multiplication and linear algebra. The * operator does that. Much of the time you are just doing simple scalar products, so things like 2*3 work perfectly well. You don't realize, or don't care that you are using a tool for matrix operations. As well, you can even multiply all the elements of a matrix or vector by a constant, again * works. So 2*ones(2,2) works just fine in MATLAB, doing what you expect.
The problem arises when you want to multiply two vectors together, when you want to form the product of all elements of each vector, one at a time, resulting in a new vector of the same length. This element-wise operation is NOT done by the * operator. MATLAB provides different operators to perform element-wise multiplication, division, and power operators. They are the .* ./ and .^ operators.
You have exactly that case. I'll write it properly here:
t = 0:pi/100:20;
x = 10.05*exp(-0.2*t).*sin(1.99*t + 1.47);
plot(t,x)
And this will now work, producing a sine wave with an exponentially decreasing amplitude.
Note that the only difference in my code was the .* operator between the exp and sin terms, because there we wanted to form the product of two sets of vector elements to form a new vector. All of the cases where I just multiplied by a scalar constant were ok using the * operator, although it is not a bad idea to get used to using it always on such problems.
I need to point out that you can add or subtract two vectors together and get an element-wise result with no need for a special operator. So +(plus) and -(minus) always work as long as the vectors are the same size and shape. For example:
a = [1 2 3];
b = [2 3 5];
a + b
ans =
3 5 8
The only thing I will add is that when you build a vector using the colon operator as you did
t = 0:pi/100:20;
the final point in that vector need not be exactly 20.
t(end)
ans =
19.9805292768311
That is because the increment is pi/100, which does divide (20-0) evenly.
A better tool to generate such vectors, where the final point will be as you desire it, is linspace. The vector you generated had 637 elements in it. If you wanted to generate a vector of some number of elements with the desired start and end points, you can do this:
t = linspace(0,20,637);
t(end)
ans =
20
The spacing in the linspace vector is close to pi/100, although not exactly so, as again, you cannot use exactly that spacing and end at exactly 20.
t(2) - t(1)
ans =
0.031447
pi/100
ans =
0.031416
As I said though, your real problem was in not using the .* operator. Don't forget about the ./ and .^ operators too.