How to debug the 'matrix dimension not agree' when solving matrix time by time using loop (with code)

조회 수: 5 (최근 30일)
I want to create a function with for-loop to keep solving a matrix by assigning the previous solution to the next matrix equation, I could only run for one time of the loop, then it showing that my matrix dimension is not agree at the 2nd loop.
Code:
function X = MatrixSolu()
X=5*ones(4,1);
A = [5 2 6 4; 9 8 6 5; 5 8 4 2; 9 5 4 6];
for i=1:12
b=X;
X=b\A;
fprintf('%14.2',X);
end

답변 (1개)

Geoff Hayes
Geoff Hayes 2016년 11월 16일
Sichen - if you step through your code, you will note that X is initially a 4x1 but after solving for X as
X = b\A;
it becomes a 1x4 array. I think that to solve this system of linear equations (as per the examples found here mldivide), you want to do something like
X=5*ones(4,1);
A = [5 2 6 4; 9 8 6 5; 5 8 4 2; 9 5 4 6];
for i=1:12
b=X;
X=A\b;
fprintf('%14.2f',X');
fprintf('\n');
end
as x = A\b solves the system of linear equations A*x = b. Though it isn't clear to me why you want to solve your equations in this manner.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by