MATLAB: How to draw a number of line in a unit cell

drawline()

I want to generate randomly dispersed number of line, that length, L, is constant and the angle of the stick is varied between (-pi/2, pi/2).
the code below is working when I select a constant angle. However, It is not working when I enter variation in theta.
k=100
x=linspace(0,1,100);
y=linspace(0,1,100);
theta=randi([-20,20],1,100);
L=0.1;
for i=1:k;
x(i)=rand;
x(i+1)-x(i)+L*cos(theta);
y(i)=rand;
y(i+1)=y(i)+L*sin(theta);
line([x(i+1) x(i)],[y(i+1) y(i)])
end
it is same with the code below as well
x=rand(1,100);
y=rand(1,100);
theta1=10;
theta2=-10;
L=0.5;
for i=1:50
x(i)=x(i+1)+L*cos(theta1);
y(i)=y(i+1)+L*sin(theta1);
line([x(i) x(i+1)],[y(i) y(i+1)])
end
x1=rand(1,100);
y1=rand(1,100);
for k=1:50
x1(k)=x1(k+1)+L*cos(theta2);
y1(k)=y1(k+1)+L*sin(theta2);
line([x1(k) x1(k+1)],[y1(k) y1(k+1)])
end

Best Answer

Use theta(i) to access the ith angle from your array theta. Also, there is no need to store line positions in x(i+1) and y(i+1) if you are just going to overwrite those values during the next iteration. How does the following work for you?
k=100;
x=rand(1,k);
y=rand(1,k);
theta=randi([-20,20],1,k);
L=0.1;
for i=1:k
t = theta(i);
line([x(i) x(i)+L*cos(t)], [y(i) y(i)+L*sin(t)])
end
Related Question