Realtime Sine Wave Visualizer in MATLAB plot Slider Control Amplitude Frequency Phase
HTML-код
- Опубликовано: 25 сен 2024
- % Create a figure window with a title
fig = figure('Name', 'Interactive Real-Time Sine Wave Plot', ...
'NumberTitle', 'off', 'Position', [100 100 800 600]);
% Create axes for plotting
ax = axes('Parent', fig, 'Position', [0.1 0.4 0.8 0.5]);
hold on;
grid on;
title('Interactive Sine Wave');
xlabel('X-axis');
ylabel('Y-axis');
% Initialize sine wave parameters
x = linspace(0, 10, 1000);
amplitude = 1;
frequency = 1;
phase = 0;
% Initial plot of the sine wave
hPlot = plot(ax, x, amplitude * sin(2 * pi * frequency * x + phase), ...
'LineWidth', 2, 'Color', 'b');
% Add interactivity: sliders, buttons, etc.
% Amplitude slider
uicontrol('Style', 'text', 'String', 'Amplitude', 'Position', [50, 150, 100, 20]);
ampSlider = uicontrol('Style', 'slider', 'Min', 0.1, 'Max', 5, ...
'Value', amplitude, 'Position', [150, 150, 150, 20], ...
'Callback', @updatePlot);
% Frequency slider
uicontrol('Style', 'text', 'String', 'Frequency', 'Position', [50, 120, 100, 20]);
freqSlider = uicontrol('Style', 'slider', 'Min', 0.1, 'Max', 5, ...
'Value', frequency, 'Position', [150, 120, 150, 20], ...
'Callback', @updatePlot);
% Phase slider
uicontrol('Style', 'text', 'String', 'Phase', 'Position', [50, 90, 100, 20]);
phaseSlider = uicontrol('Style', 'slider', 'Min', -pi, 'Max', pi, ...
'Value', phase, 'Position', [150, 90, 150, 20], ...
'Callback', @updatePlot);
% Add a play button to animate the wave
playButton = uicontrol('Style', 'pushbutton', 'String', 'Play', ...
'Position', [50, 60, 100, 30], 'Callback', @playAnimation);
% Boolean to track animation status
isAnimating = false;
%% Function to update the plot based on slider values
function updatePlot(~, ~)
amplitude = get(ampSlider, 'Value');
frequency = get(freqSlider, 'Value');
phase = get(phaseSlider, 'Value');
% Update the plot
y = amplitude * sin(2 * pi * frequency * x + phase);
set(hPlot, 'YData', y);
drawnow;
end
%% Function to animate the wave when the Play button is pressed
function playAnimation(~, ~)
if ~isAnimating
isAnimating = true;
set(playButton, 'String', 'Pause');
while isAnimating
% Slightly change the phase over time
phase = phase + 0.1;
set(phaseSlider, 'Value', phase);
% Update the plot with the new phase
updatePlot();
% Pause for a short time to create the animation effect
pause(0.05);
% If the figure is closed, stop the loop
if ~isvalid(fig)
isAnimating = false;
break;
end
end
else
isAnimating = false;
set(playButton, 'String', 'Play');
end
end
%% Close request function to stop animation when the figure is closed
function closeRequest(~, ~)
isAnimating = false; % Stop animation if the window is closed
delete(fig);
end
% Assign the custom close function
fig.CloseRequestFcn = @closeRequest;
end