フィルターのクリア

Help writing a simple function

1 回表示 (過去 30 日間)
Kristopher
Kristopher 2014 年 6 月 20 日
編集済み: per isakson 2017 年 9 月 17 日
I'm new to functions, and I was wondering how you would write a simple if, then function.
if x<4, then f(x)=-1
if 4<=x<=4 then f(x)=cos(x)
if x>4 then f(x)=1
%when an x is entered, it should give f(x) as the output. %Thank you.

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 6 月 20 日
Read the documentation, you will find examples if, elseif, else

David Sanchez
David Sanchez 2014 年 6 月 20 日
You should do as Azzi Abdelmalek says, anyway, here is your code:
if x<4
f = -1;
elseif x>=4 && x<=4
f = cos(x);
else
f = 1;
end

Andrei Bobrov
Andrei Bobrov 2014 年 6 月 20 日
編集済み: Andrei Bobrov 2014 年 6 月 20 日
function out = f(x)
out = sign(x-4);
out(~out) = cos(4);
end
use
>> out = f([- 3 5 6 4 -2 3 1 4])
out =
-1.00000 1.00000 1.00000 -0.65364 -1.00000 -1.00000 -1.00000 -0.65364

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by