필터 지우기
필터 지우기

whats wrong with this if block?

조회 수: 1 (최근 30일)
Muazma Ali
Muazma Ali 2019년 9월 8일
편집: dpb 2019년 9월 8일
% WHATS WRONG WITH THIS IF BLOCK, AM NOT GETTING UNKNOWN AS A RESULT WHERE
% IT HAS TO GIVE ME THIS RESULT. WHEN i JUST RUN THIS CODE, IT GIVE ME THIS ERROR MESAGE:
% Index exceeds matrix dimensions.
different_salts_available=input(['Enter the number associated with the chloride that is available with ZnBr2 and HCOONa, enter 0 if another chloride salt than the ones listed are available,'...
'\n1: NH4Cl,'...
'\n2: MgCl2,'...
'\n3: CaCl2,'...
'\n4: NaCl,'...
'\n5: KCl. ']);
if (different_salts_available==1||2||3||4||5)
det_beste_saltet='ZnBr2';
disp('Choose to add zinc bromide,')
disp(det_beste_saltet)
else
det_beste_saltet='unknown';
disp('Invalid number entered. The programme cannot decide the best salt based on the input entered. The best salt is:')
disp( det_beste_saltet)
end

채택된 답변

dpb
dpb 2019년 9월 8일
편집: dpb 2019년 9월 8일
(different_salts_available==1||2||3||4||5)
is bad syntax for if in MATLAB. It results in testing the result of the logical expression
(different_salts_available==1) || 2 || 3 || 4 || 5
which is always TRUE so nothing matters about what the variable value actually is.
MATLB requires the form as
if different_salts_available==1 || different_salts_available==2 || different_salts_available==3 ...
which is very verbose; you could write
if ismember(different_salts_available,1:5)
as one possible way or
if different_salts_available>=1 & different_salts_available<=5
or several other alternatives.
The latter is common enough expression I have a utility routine iswithin I use quite a bit to hide some higher level complexity
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
end
With it, the latter above becomes
if iswithin(different_salts_available,1,5)
...

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Verification, Validation, and Test에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by