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?

回答(2 个)

KSSV
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
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) ;
Ann Little
Ann Little 2018-11-28
is that done in the command windown or in the script? Is this where i create another script that displays the factors?

请先登录,再进行评论。


Stephen23
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

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by