How to use if statements for a vector?

3 ビュー (過去 30 日間)
Gavin Thompson
Gavin Thompson 2021 年 9 月 28 日
コメント済み: Walter Roberson 2021 年 9 月 28 日
if choice==2
fprintf('Converting Resistance to Color Bands');
R = input('\n\nEnter the resistance in ohms as a vector: ');
% if R(3:end)~=0
% error('Invalid resistance entered. Program terminated.')
% end
ColorBand = Resist2Color(R);
fprintf('The color bands for that resistance are %s, %s, and %s',ColorBand(1),ColorBand(2),ColorBand(3));
end
Here's my code, the part im having trouble with is the commented out section. For example, if R = [1 2 0 0] my code runs fine because the numbers after the first two columns are 0. However, if R = [0 1 0 5] my code still exceutes since MATLAB only cares if any number in my specified range is 0 and disregards those>0. How can I fix this so when there's any number after the first two that doesn't equal 0 the error pops up.

採用された回答

Walter Roberson
Walter Roberson 2021 年 9 月 28 日
if any(R(3:end)~=0)
It happens that you can abbreviate that to
if any(R(3:end))
  2 件のコメント
Gavin Thompson
Gavin Thompson 2021 年 9 月 28 日
Awesome, it worked! Do you by chance know to to make R = [1 2] work as well because currently I have it hardcoded to only work for arrays with a length of 3 or more?
Walter Roberson
Walter Roberson 2021 年 9 月 28 日
The code already posted will execute successfully as false if R is length 2.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by