Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner matrix dimensions must agree?

this is my first matlab script, so this question may seem basic and blindingly obvious, but I am a little stuck at the moment.

I have a matlab script of two lines:

x = linspace(0,4*pi,100);
y = exp(-x) * sin(x);

I'm going off the Create 2-D Line Graph tutorial on Mathworks. I want to plot f(x) = e^(-x)sin(x) over the range 0 to 4pi, but I get an inner matrix dimensions must agree error on the second line. I'm not sure what's going on, because I don't think I'm creating any matrices at the moment. Any help would be appreciated! Is there something simple with syntax that I am missing? Thanks!

like image 479
user2253332 Avatar asked Dec 03 '22 18:12

user2253332


1 Answers

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

like image 140
rayryeng Avatar answered Jan 06 '23 11:01

rayryeng