On Tue, 29 Dec 2020 at 14:03, Blaz <email@example.com> wrote:
> Hello coders
> I have a request for some sine wave code. I need to create a modified sine
> wave where I cuttof the wave at certain value and hold this until the next
> zero crossing (Please refer to the red marked line on the picture). The sine
> wave (or some other for that matter) comes in as an input vector with 20
> samples per period (this can change though from 20 to up to 40 max, but I
> don't think this has any consequence though).
> This is part of a longer code, but I can not get this section done properly.
> I would appreciate any kind of ideas.
It is always difficult to get this sort of problem right using loops.
This is not a complete solution because it does not deal with what to
do when the signal is negative, but this can be added into the
So, you want the output to be
- the signal from a zero-crossing until the signal reaches the reference value
- the reference value until the signal reaches a zero-crossing
Therefore the problem can be reduced to that of generating a signal to
toggle between the two, for example:
toggle = [0,cumsum(max(diff(s>r),0)+min(diff(s>0),0))];
# now fenerate the output signal
# and plot input and output
You will need to deal with handling the negative side of things, deal
with zero-crossing correctly and decide whether I extended toggle to
the correct length correctly for your problem.
How is this?
n_points = 200;
x = linspace(-5, 5, n_points);
y_original = sin(x);
threshold = 0.5;
% Truncate the sine wave
y_truncated = y_original.*(abs(y_original)<threshold) + threshold.*(abs(y_original)>=threshold).*sign(y_original);
y_final = y_truncated;
if y_final(k-1)==threshold && y_final(k-1)*y_final(k)>0
y_final(k) = threshold;
It produces the desired result for the test sine wave I put in.