help-octave
[Top][All Lists]

## Re: Sine wave code

 From: Brett Green Subject: Re: Sine wave code Date: Tue, 29 Dec 2020 12:54:51 -0500

On Tue, Dec 29, 2020 at 12:37 PM Ian McCallion <ian.mccallion@gmail.com> wrote:
On Tue, 29 Dec 2020 at 14:03, Blaz <blaz.pirnat@gmail.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
solution easily.

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:

s =sin(linspace(0,2*pi,400));
r=.8;
toggle = [0,cumsum(max(diff(s>r),0)+min(diff(s>0),0))];

# now fenerate the output signal
out=s.*(1-toggle)+r*toggle;

# and plot input and output
plot(1:400,s,out)

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.

Cheers... Ian

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;
for k=2:n_points
if y_final(k-1)==threshold && y_final(k-1)*y_final(k)>0
y_final(k) = threshold;
end
end

clf
plot(x, y_final)

It produces the desired result for the test sine wave I put in.