Borrar filtros
Borrar filtros

Error Using * Inner Matrix Dimensions Must agree Questions

2 visualizaciones (últimos 30 días)
Sharif
Sharif el 13 de Sept. de 2014
Editada: Matt J el 13 de Sept. de 2014
So for my assignment we were given 2 linear algebraic equations and were to put them into the equation Ax-b using matrix, make a 2D plot showing the solution, and then a 3D plot. The code I have right here has everything correct up to the 3D plot; I can't get it to work because of this error. if anyone could help me figure out what wrong that'd be great! Thanks
A=[1,2 ;2,1]
b=[2,4]'
x=inv(A)*b
x2=[-10:10]
x1=2-2.*x2
x3=2-0.5.*x2
plot(x1,x2)
plot(x3,x2)
plot(x1, x2 ,x3, x2)
x10 = -10:10
x11 = -10:10
p=zeros(length(x10), length(x11))
for i=1:1:length(x10)
for j=1:1:length(x11)
r=A*[x10;x11]'-b;/////////// This is the line I get the error
p(i,j)=r'*r
end
end
figure;
surf(p)
Error using *
Inner matrix dimensions must agree

Respuestas (1)

Geoff Hayes
Geoff Hayes el 13 de Sept. de 2014
Sharif - if you breakpoint at the line
r=A*[x10;x11]'-b;
and then run the code, you can observe the dimensions of the matrices when the debugger pauses tat this line: A is a 2x2 matrix, x10 is a 1x21 matrix, x11 is a 1x21 matrix, and b is a 2x1 matrix. This means that [x10;x11] is a 2x21 matrix and that its transpose is a 21x2. The error message is being raised because of the
A*[x10;x11]'
The code is trying to multiply a 2x2 matrix with a 21x2 matrix - the dimensions are incompatible (for multiplication) and so the Inner matrix dimensions must agree error message makes sense.
I think that you only want to be using certain elements from x10 and x11 at each iteration of the loop. Your outer for loop iterates over the length of x10 while the inner for loop iterates over the length of x11. This suggests that your code should read
for i=1:1:length(x10)
for j=1:1:length(x11)
r=A*[x10(i);x11(j)] - b;
p(i,j)=r'*r;
end
end
Note the only differences in the above is the [x10(i);x11(j)] and the removal of the transpose from this 2x1 matrix.
The code should now run to completion and the surf function will plot the data (and hopefully appear as you expect!).

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by