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

1 次查看(过去 30 天)
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)

采纳的回答

Stephen23
Stephen23 2022-1-28
编辑:Stephen23 2022-1-28
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by