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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by