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

5 ビュー (過去 30 日間)
Sichen Wang
Sichen Wang 2016 年 11 月 16 日
回答済み: Geoff Hayes 2016 年 11 月 16 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by