I'm trying to make a function and my if statement isn't working properly

1 view (last 30 days)
Hello,
I'm trying to make a function to create unit steps. I think I have it almost working but for some reason it wont execute the if statement that is inside my for loop. It goes straight to the else statement and executes y = 0 across the time values when I plot them. I'm trying to find out why it wont go to one when a >= mu. I've been looking on the internet to find something but I cant seem to. Thanks.
function y = my_unit_step(t,mu)
a = t;
y = length(a); % y outputs same size as t
for i = 1:length(a)
if a >= mu
y(i)=1;
else
y(i)=0;
end
end
plot (t,y)

Accepted Answer

Stephen23
Stephen23 on 28 Jan 2022
Edited: Stephen23 on 28 Jan 2022
Assuming that mu is scalar:
if a(i) >= mu
% ^^^ you need this indexing
Note that the MATLAB approach would be to get rid of the loop entirely, e.g.:
y = double(a>=mu);

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!