MATLAB: Accessing elements in a matrix to use in a for loop

for loop

Hello all, I seem to have a problem in regards to assigning a value from a matrix I created to a certain variable using a for loop. I am using different pairs of angles to create a plot and I want to access those elements in the for loop to generate values for Q1 and Q2.
L1=input('Enter the length of Link 1:' );
L2=input('Enter the length of Link 2:' );
i=0:5:180;
j=0:5:180;
[p,q] = meshgrid(i, j);
pairs = [p(:) q(:)];
for k = 1 : size(pairs)
Q1(k)=pairs(k,1);
Q2(k)=pairs(k,2);
PEx(k)=(L1.*cosd(Q1))+(cosd(Q1).*cosd(Q2).*L2);
PEy(k)=(L1.*sind(Q1))+(sind(Q1).*cosd(Q2).*L2);
PEz(k)=(-L2.*sind(Q2));
end
Error:
"In an assignment A(:) = B, the number of elements in A and B must be the same."

Best Answer

L1=input('Enter the length of Link 1:' );
L2=input('Enter the length of Link 2:' );
i=0:5:180;
j=0:5:180;
[p,q] = meshgrid(i, j);
pairs = [p(:) q(:)];
PEx = zeros(1,size(pairs,1)) ;
PEy = zeros(1,size(pairs,1)) ;
PEz = zeros(1,size(pairs,1)) ;
for k = 1 : size(pairs,1)
Q1=pairs(k,1);
Q2=pairs(k,2);
PEx(k)=(L1.*cosd(Q1))+(cosd(Q1).*cosd(Q2).*L2);
PEy(k)=(L1.*sind(Q1))+(sind(Q1).*cosd(Q2).*L2);
PEz(k)=(-L2.*sind(Q2));
end
You need not to use a loop for that...Simply use:
PEx=(L1.*cosd(pairs(:,1)))+(cosd(pairs(:,1)).*cosd(pairs(:,2)).*L2);
PEy=(L1.*sind(pairs(:,1)))+(sind(pairs(:,1)).*cosd(pairs(:,2)).*L2);
PEz=(-L2.*sind(pairs(:,2)));