I have created a function with y as the output and x as input. how do i put statements saying that if x < 0, y = 0; if x > 0, y = 1; if x = 0, y = .5. I have done it trying to do three separate if statements within the same function as shown below.
7 次查看(过去 30 天)
显示 更早的评论
function [y] = HeavisideFunct(x)
y = 0
if x < 0
disp(y)
end
y = 1
if x > 0
disp(y)
end
y = 0.5
if x == 0
disp(y)
end
end
I was thinking about using 3 different y outputs, but im not sure if that is allowed given that the question being asked doesnt say there is multiple outputs. Does there have to be?
1 个评论
回答(2 个)
KSSV
2018-11-28
function [y] = HeavisideFunct(x)
if x < 0
y = 0 ;
disp(y)
elseif x > 0
y = 1 ;
disp(y)
elseif x == 0
y = 0.5 ;
disp(y)
end
end
3 个评论
KSSV
2018-11-28
YOu have to save the function on the name, HeavisideFunct.m..go to the folder where it is saved..and call it by:
x = 1.5 ;
y = HeavisideFunct(x) ;
Stephen23
2018-11-28
编辑:Stephen23
2018-11-28
The proper MATLAB solution would be to vectorize your code, which efficiently allows for the input to be an array of any size:
>> myheaviside = @(x) 0.5*(x==0) + (x>0);
>> myheaviside([-1,0,1])
ans =
0.00000 0.50000 1.00000
2 个评论
Rik
2018-11-28
The first line defines an anonymous function. If you don't know what that is, you can follow the second link Stephen posted.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!