This is a very simple error to resolve, and I'll admit that it's a common error that most MATLAB programmers face when facing MATLAB for the first time. Specifically, when you do this line:
y = exp(-x) * sin(x);
This operation is assuming that you will perform a matrix multiplication. What you actually want to do is an element-by-element operation. You want the points in exp(-x)
to multiply with the corresponding elements in sin(x)
. @ellieadam provided some nice links for you to review what these operations are, but if you want to do element-by-element operations, you need to add a dot (.
) before the multiplication operator. As such, you need to do this instead:
y = exp(-x) .* sin(x); %// Note the dot!
This line should now work.
As a bonus for you, here's a simple example. Suppose I have these two matrices:
A = [1 2;
3 4];
B = [4 3;
2 1];
By doing A * B
in MATLAB, you get:
>> A * B
ans =
8 5
20 13
Note that this will perform a matrix multiplication. By doing A .* B
, this is what I get:
>> A .* B
ans =
4 6
6 4
What's different with this statement is that one element in A
is multiplied by the corresponding element in B
. The first row and first column of A
gets multiplied by the first row, first column of B
, and the same location in the output matrix is where this result is stored. You can follow along with the other elements in the output matrix and it'll give you the same behaviour. There are other element-by-element operations, such as division and exponentiation. Addition and subtraction are inherently element-by-element, as performing these operations on matrices is by definition in this fashion.
To add to @ellieadam's post, check this MathWorks post out that specifically shows you the various operations on matrices and vectors, including element-by-element operations:
http://www.mathworks.com/help/matlab/matlab_prog/array-vs-matrix-operations.html
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…