I have problem with while loop.

1 回表示 (過去 30 日間)
Tran Thien
Tran Thien 2021 年 11 月 17 日
コメント済み: Chunru 2021 年 11 月 17 日
So I have homework about Gaussian Elimination, when input matrix b I want to ensure that the input matrix has the same number of rows as matrix A and it must be in a column matrix so I tried these code with while loop:
A=input('Input matrix A');
b=input('Input matrix b in column form');
szA=size(A)
szb=size(b)
while (szb(1,1)~=szA(1,1) && szb(1,2)~=1)
b=input('Matrix b is not in column form,please re-input');
szb=size(b)
if (szb(1,1)==szA(1,1)&& szb(1,2)==1)
break
end
end
Ab=[A b]
My goal here is when the input matrix b has a different number of rows than that of matrix A and/or the number of columns is not equal to 1 then the user has to re-enter the matrix. When both conditions are met then break the while loop and continue.
But when I tested with matrices like:
A=[1 2;2 1] b=[1 2;2 1]
The while loop still break and give me matrix Ab.
Or
A=[1 2;2 1] b=[1;2;3]
The while loop breaks and the program gives me the horzcat error (I understand that matrix b don't have the same number of rows as matrix A will cause this error)
Please help. Thank you.

採用された回答

Chunru
Chunru 2021 年 11 月 17 日
Make the following change:
%while (szb(1,1)~=szA(1,1) && szb(1,2)~=1)
while (szb(1,1)~=szA(1,1) || szb(1,2)~=1)
  2 件のコメント
Tran Thien
Tran Thien 2021 年 11 月 17 日
It works! Thank you very much.
Chunru
Chunru 2021 年 11 月 17 日
To make your code easer to read, you can chnage szb(1,1) to szb(1) and so on.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by