I have problem with while loop.

1 Ansicht (letzte 30 Tage)
Tran Thien
Tran Thien am 17 Nov. 2021
Kommentiert: Chunru am 17 Nov. 2021
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.

Akzeptierte Antwort

Chunru
Chunru am 17 Nov. 2021
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 Kommentare
Tran Thien
Tran Thien am 17 Nov. 2021
It works! Thank you very much.
Chunru
Chunru am 17 Nov. 2021
To make your code easer to read, you can chnage szb(1,1) to szb(1) and so on.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by