generate sine waves that appears after one another

1 view (last 30 days)
Hello Everyone,
I want to generate sine waves in while loop with changeable values. The Problem is that with each repetition, a new signal is being generated. What i want is that the new Signal appears infront of the old one, so if my time is 1 sec, and i have the magnitude 1, the first signal should be in time intervall (0-1) with 1 magnitude and the next signal from (1-2) with the increased magnitude.
I have written the following code:-
f = 1;
a = 0.1;
Fs = 1000;
t1 = 1;
figure;
while 1 % Runs until you press Ctrl-c
t = 0 : 1/Fs :t1-1/Fs;
x = a * sin(2 * pi * f * t);
plot(t, x);
drawnow; % Give Matlab a chance to display changes
t1 = t1 + 1;
a=a+0.1;
end
If you have any ideas, i would be happy if you share with me.
Regards
Ali

Answers (3)

Jan
Jan on 28 Jun 2022
Edited: Jan on 28 Jun 2022
figure;
% Insert this:
axes('NextPlot', 'add'); % Equivalent to: hold('on')
...
Otherwise the plot() command clears its axes before plotting.

Neeraj Mirji
Neeraj Mirji on 28 Jun 2022
The following code will generate the new sine wave in the same plot.
f = 1;
a = 0.1;
Fs = 1000;
t1 = 1;
figure;
while 1 % Runs until you press Ctrl-c
t = (t1-1) : 1/Fs :t1-1/Fs;
x = a * sin(2 * pi * f * t);
plot(t, x);
hold on;
drawnow; % Give Matlab a chance to display changes
t1 = t1 + 1;
a=a+0.1;
end
Hope it helps.

Pratyush Swain
Pratyush Swain on 29 Jun 2022
I believe you want to visualise the various amplitudes of sin wave in continous segments, that is the first signal should be in time intervall (0-1) with 1 magnitude and the next signal from (1-2) with the increased magnitude and so on.
As mentioned by @Jan, you can use the axes command to add to the same plot and you can also follow the given method to visualize in a better manner
f = 1;
a = 0.1;
Fs = 1000;
t1 = 1;
figure;
axes('NextPlot', 'add');
while 1 % Runs until you press Ctrl-c
%since we want to visualise the new amplitude in the segment-[t1-1,t1]%
t_array = t1-1 : 1/Fs :t1-1/Fs;
x = a * sin(2 * pi * f * t_array);
plot(t_array, x);
%add pause to visualise the graph as amplitude grows%
pause(1);
t1 = t1 + 1;
a=a+0.1;
end
Hope this helps and satisfies your requirements.

Community Treasure Hunt

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

Start Hunting!

Translated by