If Statement not working

14 ビュー (過去 30 日間)
isabella Anglin
isabella Anglin 2020 年 10 月 16 日
コメント済み: Ameer Hamza 2020 年 10 月 16 日
Hello,
I am new to matlab and have a very, very basic issue. This is a simplified function, but it illustrates the problem I have in my other function.
Matlab seems to bypass my if conditions. Here is the function:
function y = functry(x)
Speed = 100;
if (x> 100)
Speed = 50;
end
y = Speed * x;
end
However, the Speed is taken to be 100 even when I input a high range, for example:
y_try = functry(1:150)
plot(1:150, y_try)
Here is still get a linear plot and no change for the Speed when x>100.
Any help would be much appreciated! Thank you!

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 10 月 16 日
編集済み: Ameer Hamza 2020 年 10 月 16 日
If x is a vector then the line
if (x> 100)
does not work as expected. The correct syntax is
function y = functry(x)
Speed1 = 100;
Speed2 = 50;
mask = x > 100;
y = (~mask)*Speed1.*x + mask*Speed2.*x;
end
  4 件のコメント
isabella Anglin
isabella Anglin 2020 年 10 月 16 日
Okay great thank you!
However, eventually in my function i'll want to have multiple "Speeds". Do i just make additional masks then?
Ameer Hamza
Ameer Hamza 2020 年 10 月 16 日
Yes. Let me show you a more general approach
function y = functry(x)
Speed1 = 100;
Speed2 = 50;
mask1 = x < 100;
mask2 = x >= 100;
y = (mask1)*Speed1.*x + mask2*Speed2.*x;
end
Just keep making a mask like this, and it will work. Note that If you want to have a condition that x is between 150 to 250, then the correct syntax to write that is
mask = (150 < x) & (x < 250) % mask = 150 < x < 250 is a common mistake.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by