2
votes

I have a matrix A and a vector x:

A is a 50x30 matrix

x is a 1x30 vector

I want to multiply A by x, yet whenever I try z = A * x I get the error Inner matrix dimensions must agree. Yet surely with the same amount of columns the matrix dimensions do agree?

I'm confused as to why this works:

A = rand(2,2);
x = [1;2];
A * x

Yet this does not work:

A = rand(2,2);
x = 1:2;
A * x
4

4 Answers

5
votes

Transpose the second argument:

z = A * x.'

As the error suggest - the inner matrix dimensions must agree - you have A = [50x30] and x = [1x30], the inner dimensions are 30 and 1.

By tranposing you get A = [50x30] and x = [30x1], the inner dimensions are then 30 and 30, agreeing.

1
votes

In your first example, x is 2 by 1. In the second example, x is 1 by 2.

Notice you are using ;(semi-colon) in first example and :(colon) in the second example. You may verify the dimensions by size(x) for both examples.

1
votes

In order to multiply A by a vector from the right the vector must be 30-by-1 and not 1-by-30 - this is the reason for the error you are getting. To solve

z = A * x.';
0
votes

x = [1;2]; creates a column vector [1;2]. In contrast, the command x = 1:2; creates a row vector [1 2]. Because of that, the matrix multiplication fails for the second example.