Generating a single pulse in time?
Show older comments
Hi I would like to write a simple code for a single pulse.So for example: if I would like to see pulse in the time period: 400<t<500
Why does If (t>400&&t<500) s=2.0 else s=0.0 end
When I plot this I get: a result where s=0 for all time and no pulse.
but
if (t>400&&t<500) s=2.0; else s=0.01; end
a pulse with a baseline of 0.01 (and maximum value 2.0)?
Thank you for your help.
Accepted Answer
More Answers (5)
Wayne King
on 28 Nov 2013
Edited: Wayne King
on 28 Nov 2013
You did not tell us the sampling frequency so I'll just assume it is 1 Hz in my example.
t = 0:1:1000;
s = 0.01*ones(length(t));
s(t>400 & t<500) = 2;
plot(t,s)
Note that in this case you could just do the simpler (assuming the first sample is t=0):
s = 0.01*ones(10001,1);
s(402:500) = 2;
but the example I have should work when the sampling frequency is not 1.
2 Comments
AA
on 28 Nov 2013
Talha Khalid
on 9 Nov 2020
@Wayne King
I just tested your answer. It doesn't generate the required result. See the attached picture

David Sanchez
on 28 Nov 2013
It is easier to do:
t = 0:1000;
s = zeros(length(t));
s(t>400 & t<500) = 2;
plot(t,s)

AA
on 28 Nov 2013
0 votes
Wayne King
on 28 Nov 2013
See my earlier answer for how to do it.
Using your if statement approach, when t is a vector how do you expect the if statement to evaluate (t> 400 && t<500)?
To get that approach to work you'd have to loop through the t-values like this
s = zeros(1000,1);
t = 1:1000;
for nn = 1:length(t)
tval = t(nn);
if (tval > 400 && tval<500)
s(nn) = 2;
else
s(nn) = 0.01;
end
end
plot(t,s)
But that is not an efficient use of MATLAB's inherit array operations. Use the approach I gave you earlier.
AA
on 28 Nov 2013
Categories
Find more on Descriptive Statistics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!