How can I Compare a Signal with some Threshold Value as comparator to give output as 0 or 1?
Show older comments
i want to Compare random sine singnal with some threshold value, ust as a comparator working. I want the output to be 1 if its above the Threshold Value or0 if its below threshold value.
Can somebody kindly check why is this code not working?
% Random Sine Signal to compare with Threshold Value:
Fs = 8000; % samples per second
dt = 1 / Fs; % seconds per sample
StopTime = 0.25; % seconds
t = (0: dt: StopTime-dt) '; % seconds
%% Sine wave:
Fc = 60; % hertz
x = cos (2 * pi * Fc * t);
out = zeros (size (t)); % Array to Show output less then ot greater then Threshold Value
for k = 1: 1: numel (t)
if (x> 0.5) % comparin signal with Thresold lets suppose 0.5
out (k) = 1; % If True
else
out (k) = 0; % If false
end
end
plot (t, x)
hold on
plot (t, out)
Answers (1)
Star Strider
on 19 Aug 2020
Subscript ‘x’ as well to use the loop:
out = zeros (size (t)); % Array to Show output less then ot greater then Threshold Value
for k = 1: 1: numel (t)
if (x(k)> 0.5) % comparin signal with Thresold lets suppose 0.5
out (k) = 1; % If True
else
out (k) = 0; % If false
end
end
however this is much more efficient and produces the same result:
out = x > 0.5;
.
6 Comments
Syed Adeel
on 20 Aug 2020
Star Strider
on 20 Aug 2020
If you want ‘out’ to be either 0 or 0.001, this will work with both your loop and my logical vector:
out = out * 0.001;
The problem is that the 1 mV signal is difficult to see on that plot.
One option would be:
out = out * 0.001;
figure
yyaxis left
plot (t, x)
yyaxis right
plot (t, out)
The yyaxis function was introduced in R2016a. If you have an earlier version, use plotyy with different syntax.
.
Syed Adeel
on 24 Aug 2020
Star Strider
on 24 Aug 2020
I have no idea where you want to put this or what you want to do with it:
if x > 0.3 = 1;
else if x <0.27 =0;
I would just do:
out = 1*(x > 0.3) + 0*(x < 0.27);
or something similar.
What is ‘out’ (or whatever you want to call it in your code) supposed to be in the gap between 0.27 and 0.3?
I have no idea what you are doing.
Syed Adeel
on 24 Aug 2020
Star Strider
on 24 Aug 2020
I have no idea how to interpret that diagram.
Categories
Find more on Programming 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!