Piece-wise handle function help

3 ビュー (過去 30 日間)
Steve
Steve 2012 年 8 月 8 日
Hello Dear Experts,
Consider I have a piece wise function and I want to create it using handle @ and pass it to another function, please guide me how to do this.
For example, how to define: f = @(x) x^2 if x<0, -x^2 if x>0
and to pass it to another function: func(f) After passing the function to the func, I need to be able to operate with it
for example:
function res = func(f)
res = f(5);
end

回答 (2 件)

per isakson
per isakson 2012 年 8 月 9 日
編集済み: per isakson 2012 年 8 月 9 日
Try
>> cssm
ans =
-25
where in one m-file, cssm.m
function y = cssm
y = foo( @piece_wise );
end
function r = piece_wise( x )
if x < 0
r = x*x;
else
r = -x*x;
end
end
function r = foo( f )
r = f(5);
end
The three function may be defined in separate m-files

Matt Fig
Matt Fig 2012 年 8 月 9 日
It is not terribly efficient, but can be done:
f = @(x) (x.^2).*(x<0)-(x.^2).*(x>=0);
x = -10:.001:10;
plot(x,f(x))
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2012 年 8 月 9 日
f1 = @(x)-sign(x).*x.^2

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by