Help about function with if statement

I have problem with creating function. I don´t know how to use command function properly. Can you guys tell me where I was wrong it will be very helpful
function [y]=task1(x)
if x>=8
y = 14*(5*x)^(1/2)+9;
end
if (-1<=x<8)
y=9*x +9;
end
if (x<-1) y=9;
end

1 件のコメント

Jan
Jan 2016 年 12 月 18 日
Why do you assume, that something is wrong? Which problem do you observe? Do you get an error message?

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

回答 (2 件)

laaj
laaj 2016 年 12 月 18 日

0 投票

function output=task1(x)
if x>=8
y = 14*(5*x)^(1/2)+9;
end
if (-1<=x<8)
y=9*x +9;
end
if (x<-1)
y=9;
end
output=[y];
I don't know much but I just hope it will solve the problem.
Jan
Jan 2016 年 12 月 18 日
編集済み: Jan 2016 年 12 月 18 日

0 投票

"if (-1<=x<8)" does most likely not do, what you expect. Matlab processes this expression from left to right: "-1<=x" replies TRUE or FALSE depending on the value of x. In the next step you have "TRUE<8" or "FALSE<8". While TRUE is converted to 1, FALSE is a 0, and both values are smaller than 8. You need two comparisons: "-1 <= x" and "x < 8":
function y = task1(x)
if x >= 8
y = 14 * (5 * x)^(1 / 2) + 9;
elseif -1 <= x && x < 8
y = 9 * x + 9;
elseif x < -1
y = 9;
end
Now you can simplify this: If you have excluded x>=8 already, you do not have to check for x<8 anymore:
function y = task1(x)
if x >= 8
y = 14 * sqrt(5 * x) + 9; % SQRT is cheaper than ^0.5
elseif -1 <= x
y = 9 * x + 9;
else
y = 9;
end

カテゴリ

ヘルプ センター および File ExchangeProgramming Utilities についてさらに検索

タグ

質問済み:

2015 年 11 月 18 日

編集済み:

Jan
2016 年 12 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by