问题
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
回答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.
回答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.
回答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.';
回答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.
来源:https://stackoverflow.com/questions/28850858/inner-matrix-dimensions-must-agree