MATLAB: Question about plots using meshgrids.

dimensionMATLABmeshgridplot

I've created a plot which can show the range of the tip's movement from a 2-armed robotic arm and I hope to add one more arm.
The correct code which can plot 2 arms shows as follows:
l1 = 10; % length of first arm

l2 = 7; % length of second arm

theta1 = 0:0.1:pi/2;% all possible theta1 values

theta2 = 0:0.1:pi;% all possible theta2 values

[THETA1, THETA2] = meshgrid(theta1, theta2); % generate a grid of theta1 and theta2 values

X = l1 * cos(THETA1) + l2 * cos(THETA1+THETA2) ; % compute x coordinates



Y = l1 * sin(THETA1) + l2 * sin(THETA1+THETA2) ;
for theta1 = 0:0.1:pi/2;
for theta2 = 0:0.1:pi;
X = l1 * cos(THETA1) + l2 * cos(THETA1+THETA2); % compute x coordinates
Y = l1 * sin(THETA1) + l2 * sin(THETA1+THETA2);
plot (X,Y);
hold on
end
end
The result after running shows as the figure
And here's the incorrect one with 3 arms:
l1 = 10; % length of first arm
l2 = 7; % length of second arm
l3 = 6;
theta1 = 0:0.1:pi/2;% all possible theta1 values
theta2 = 0:0.1:pi;% all possible theta2 values
theta3 = 0:0.1:pi;
[THETA1, THETA2, THETA3] = meshgrid(theta1, theta2,theta3); % generate a grid of theta1 and theta2 values
X = l1 * cos(THETA1) + l2 * cos(THETA1+THETA2) + l3 * cos(THETA1+THETA2+THETA3) ; % compute x coordinates
Y = l1 * sin(THETA1) + l2 * sin(THETA1+THETA2) + l3 * sin(THETA1+THETA2+THETA3) ;
for theta1 = 0:0.1:pi/2;
for theta2 = 0:0.1:pi;
for theta3 = 0:0.1:pi;
X = l1 * cos(THETA1) + l2 * cos(THETA1+THETA2) + l3 * cos(THETA1+THETA2+THETA3); % compute x coordinates
Y = l1 * sin(THETA1) + l2 * sin(THETA1+THETA2) + l3 * sin(THETA1+THETA2+THETA3);
plot (X,Y);
hold on
end
end
end
The error is that" Error using plot Data cannot have more than 2 dimensions."

Best Answer

You do not need those three nested for loops: you calculate the same thing in every iteration of the loop. You can just use
X = l1 * cos(THETA1) + l2 * cos(THETA1+THETA2) + l3 * cos(THETA1+THETA2+THETA3); % compute x coordinates
Y = l1 * sin(THETA1) + l2 * sin(THETA1+THETA2) + l3 * sin(THETA1+THETA2+THETA3);
with no loops.
But then you end up with X and Y both three dimensional; what it means to plot that is not well defined. But you could try
X1 = reshape(X, size(X,1), size(X,2)*size(X,3));
Y1 = reshape(Y, size(Y,1), size(Y,2)*size(Y,3));
plot(X1, Y1)