To keep the path of point D visible throughout the entire simulation, we can accumulate the coordinates of point D during each iteration of the loop and plot them all together after the loop completes. Here is a modified version of the code which implements this:
% Initialize arrays to store the path of point D
xD_path = [];
yD_path = [];
for theta2 = 3.316:0.1:11.316
% Function that solves the unknown variables for each value of theta2:
[theta3, r3, theta5, r6, theta4] = theta(theta2, theta3, r3, theta5, r6, theta4);
% Values of data measured:
r3values(forcount) = r3;
r6values(forcount) = r6;
t3values(forcount) = theta3;
t5values(forcount) = theta5;
t4values(forcount) = theta4;
% Calculate the coordinates of point D
xD = r4 * cos(theta3) + rd5 * cos(theta5 + thetaoff5);
yD = r1 + r4 * sin(theta3) + rd5 * sin(theta5 + thetaoff5);
% Store the coordinates of point D
xD_path = [xD_path, xD];
yD_path = [yD_path, yD];
% Plotting the mechanism
hold off; % Clear the plot for the current frame
% Link r2 (Driving link)
plot([r2*cos(theta2) 0], [r2*sin(theta2) 0], 'bo-'); hold on;
% Link r3
plot([r1*cos(theta1) r2*cos(theta2)], [r1*sin(theta1) r2*sin(theta2)], 'bo-'); hold on;
% Link r4
plot([r1*cos(theta1) r4*cos(theta4)], [r1*sin(theta1) 0.9+r4*sin(theta4)], 'bo-'); hold on;
% Vector rD
plot([r1*cos(theta1) xD], [r1*sin(theta1) yD], 'bo-'); hold on;
% r6
plot([r4*cos(theta4) r6*cos(theta6)], [0.9+r4*sin(theta4) 0.9+r6*sin(theta6)], 'bo-'); hold on;
% Plot the path of point D
plot(xD_path, yD_path, '--g', 'LineWidth', 1.5);
% Formatting
axis([-5 5 -5 5]);
grid on;
pbaspect([1 1 1]);
pause(0.1);
forcount = forcount + 1;
end
% Final plot of the path of point D
figure;
plot(xD_path, yD_path, '--g', 'LineWidth', 1.5);
xlabel('x');
ylabel('y');
title('Path of Point D');
axis([-5 5 -5 5]);
grid on;
pbaspect([1 1 1]);
Please refer to the following documentation for more information on the 'plot' function: https://www.mathworks.com/help/matlab/ref/plot.html
I hope this helps!