Here is the code I wrote. I hope it will be useful for everyone;
clear all;
clc;
radiusofcrank = 1;
angular_velocity = 60; % angular velocity in radians per second
figure;
% Sine Wave parameters
wave_amplitude_sine = 1; % Amplitude of the sine wave
wave_frequency = 0.1; % Frequency of the sine wave (in Hz)
h_sine = plot(0, -5, 'b-', 'LineWidth', 2); % Initialize with a single point
title('Buoy Motion with respect to Sine wave');
xlabel('X-coordinate');
ylabel('Y-coordinate');
grid on;
hold on;
h_crank = plot(0, 0, 'ro-', 'MarkerSize', 10, 'LineWidth', 2);
h_buoy = plot(0, 0, 'go', 'MarkerSize', 20, 'MarkerFaceColor', 'g');
h_rod = plot([0, 0], [0, 0]);
h_radius = plot([0, 0], [0, 0]);
h_circle = plot(0, 0, 'black', 'LineWidth', 2);
% Set the x-axis limits
xlim([-2, 2]);
% Set the y-axis limits
ylim([-6, 2]);
% Initialize circle coordinates outside the loop
circle_x_fixed = radiusofcrank * cos(linspace(0, 2*pi, 100));
circle_y_fixed = radiusofcrank * sin(linspace(0, 2*pi, 100));
% Update circle outside the loop
set(h_circle, 'XData', circle_x_fixed, 'YData', circle_y_fixed);
for t = linspace(0, 1, 1000)
t_s = 0:1:100;
% Update the phase of the sine wave based on time
phase = 2 * pi * wave_frequency * t;
% Calculate x-coordinates of the sine wave based on time (horizontal motion)
x_sine = t_s - 100 * t;
% Update the sine wave plot
set(h_sine, 'XData', x_sine, 'YData', wave_amplitude_sine * sin(2 * pi * wave_frequency * t_s + phase) - 5);
% Crank motion
x_crank = radiusofcrank * cos(angular_velocity * t);
y_crank = radiusofcrank * sin(angular_velocity * t);
% Buoy motion
x_buoy = 0;
y_buoy = y_crank - 5;
% Update plot objects
set(h_crank, 'XData', x_crank, 'YData', y_crank);
set(h_buoy, 'XData', x_buoy, 'YData', y_buoy);
set(h_rod, 'XData', [x_crank, x_buoy], 'YData', [y_crank, y_buoy]);
set(h_radius, 'XData', [0, x_crank], 'YData', [0, y_crank]);
% Set the y-axis limits
ylim([-6, 2]);
pause(0.01);
end
hold off;
You can adjust the sine wave to make the buoy makes up and down correctly.