How can I create a 2D plot using a parfor loop?

25 views (last 30 days)
I have some code that works as expected in a for-loop, but I would like to know if I can procude the same results instead using a parfor-loop.
I am new to parfor-loops so please inform me if I am using this featture incorrectly.
This code works as expected and produces an adequate plot:
L1 = 10;
L2 = 5;
L3 = 3;
theta1 = (0:5:90);
theta2 = (0:5:180);
theta3 = (0:5:180);
[THETA1,THETA2] = meshgrid(theta1,theta2);
figure
hold on
for i = 1:length(theta3)
THETA3 = theta3(i);
x = L1*cosd(THETA1) + L2*cosd(THETA1-THETA2) + L3*cosd(THETA1-THETA3);
y = L1*sind(THETA1) + L2*sind(THETA1-THETA2) + L3*sind(THETA1-THETA3);
plot(x,y)
end
hold off
xlabel('x')
ylabel('y')
title('Inverse Kinematic Plot of a 3-Bar Linkage')
Using the parfor-loop the code breaks down and my plot is completly empty:
L1 = 10;
L2 = 5;
L3 = 3;
theta1 = (0:5:90);
theta2 = (0:5:180);
theta3 = (0:5:180);
[THETA1,THETA2] = meshgrid(theta1,theta2);
figure
hold on
parfor i = 1:length(theta3)
THETA3 = theta3(i);
x = L1*cosd(THETA1) + L2*cosd(THETA1-THETA2) + L3*cosd(THETA1-THETA3);
y = L1*sind(THETA1) + L2*sind(THETA1-THETA2) + L3*sind(THETA1-THETA3);
plot(x,y)
end
hold off
xlabel('x')
ylabel('y')
title('Inverse Kinematic Plot of a 3-Bar Linkage')

Answers (1)

KSSV
KSSV on 22 Mar 2019
YOu cannot see the plot..but you can save it and late access it.
L1 = 10;
L2 = 5;
L3 = 3;
theta1 = (0:5:90);
theta2 = (0:5:180);
theta3 = (0:5:180);
[THETA1,THETA2] = meshgrid(theta1,theta2);
figure
hold on
parfor i = 1:length(theta3)
THETA3 = theta3(i);
x = L1*cosd(THETA1) + L2*cosd(THETA1-THETA2) + L3*cosd(THETA1-THETA3);
y = L1*sind(THETA1) + L2*sind(THETA1-THETA2) + L3*sind(THETA1-THETA3);
plot(x,y)
saveas(gcf,['Plot' num2str(i) '.fig']);
end
hold off
xlabel('x')
ylabel('y')
title('Inverse Kinematic Plot of a 3-Bar Linkage')
  2 Comments
ahmad eldeeb
ahmad eldeeb on 7 Nov 2021
what if I want to keep them all in one figure?
O.Hubert
O.Hubert on 15 Feb 2022
@ahmad eldeeb add hold on at the end of the plot line. Like this:
plot(x,y); hold on;

Sign in to comment.

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!