[Solved] Inner matrix dimensions must agree

I have a matrix A and a vector x:

A is a 50×30 matrix

x is a 1×30 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
Enquirer: JmJ


Solution #1:

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.

Respondent: Robert Seifert

Solution #2:

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.

Respondent: lonstud

Solution #3:

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.';
Respondent: Shai

Solution #4:

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.

Respondent: MarcelSimon

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.