I need to create a function named 'HeavisideFunct' which requires a single input x, and outputs y, which is the Heaviside step function (Equation 5). Where H(x) = 0 for x<0; 1 for x > 0; 0.5 for x = 0.

2 次查看(过去 30 天)
I have done the following, and it gives me an answer for y when a variable for x is inputed, but I need to be able to show that any array for x can be inputed not just x = [-10:10]. I am not sure what to use to represent x in order to do this. Do I need to introduce a new variable?
function [y] = HeavisideFunct(x)
y = [0,0.5,1];
for x = [-10:10]
if x < 0
y = 0;
disp(y);
elseif x > 0
y = 1;
disp(y);
elseif x == 0
y = 0.5;
disp(y);
end
end
end

回答(1 个)

Akira Agata
Akira Agata 2018-12-3
How about the following?
function y = HeavisideFunct(x)
y = zeros(size(x));
% x < 0
idx = x < 0;
y(idx) = 0;
% x > 0
idx = x > 0;
y(idx) = 1;
% x = 0 (assuming floating-point relative accuracy)
idx = abs(x) < eps;
y(idx) = 0.5;
end

Community Treasure Hunt

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

Start Hunting!

Translated by