MATLAB: Matlab taking too much time

simple codetoo much time

Im doing a ray tracing in matlab with this code. It is taking more 6+ hours to complete. Can anyone help
for j=1:sm
for i=1:lns2
m=-1;
P0=SM(j,:);
P1=LNS2(i,:);
OBJ=(P1-F1)/norm(P1-F1);
ILL=(P1-P0)/norm(P1-P0);
OUT=m*(OBJ-Rray1)+ILL;
t=sym('t');
RAY=P1+t*OUT;
EQN=RAY(1)==D2;
t0=solve(EQN,t);
P2=subs(RAY,t,t0);
a1=find(P2(2)<=Y2max);
a2=find(P2(2)>=Y2min);
a3=find(P2(3)<=Z2max);
a4=find(P2(3)>=Z2min);
if a1*a2*a3*a4==1
OBJ=(F2-P2)/norm(F2-P2);
ILL=(P2-P1)/norm(P2-P1);
OUT=m*(OBJ-Rray2)+ILL;
RAY=P2+t*OUT;
EQN=RAY(1)==D3;
t0=solve(EQN,t);
P3=subs(RAY,t,t0);
a1=find(P3(2)<=Ymax);
a2=find(P3(2)>=Ymin);
a3=find(P3(3)<=Zmax);
a4=find(P3(3)>=Zmin);
if a1*a2*a3*a4==1
y=norm(P1-P0)+norm(P2-P1)+norm(P3-P2);
y=sin(y*2*pi);
P3=(round(P3*M))/M;
IY=1+M*(Ymax-P3(2));
IZ=1+M*(Zmax-P3(3));
IMGMTRX(IY,IZ)=IMGMTRX(IY,IZ)+y;
end
end
end
end

Best Answer

Why not learn to use the profile tool? That will tell you where the bottlenecks lie, where you need to work to improve your code.
If I had to guess though, your first obvious problem is in the solve. You are using a symbolic tool to solve a problem (REPEATEDLY!) that is surely solvable using other tools. Or, do the symbolic solve up front, ONCE. That will hopefully give you a simple formula you can then use. At worst, consider a numerical solver.
Symbolic tools tend to be slow. I'm sure there are other problems, but that is the glaring one.
But do you really need the accuracy of a symbolic solve anyway? At the end, it appears you are rounding your results to turn into pixels. Symbolic is wild overkill here.