If you want to calculate the lengths of just the line segments labelled A to J, then you need to do it in 2 stages - first A to F as you keep lat constant and the G to J as you keep lon constant. Also, I don't think you need the assignments for a5 and b5 inside the loop. So I would do it like this:
% -----------
a5= 2.227804;
b5=103.35091;
i=1;
p1 = 3.682043;
for p2=101.523710:0.5:103.735091
AtoF(i) = distance(p1,p2,a5,b5); %% this function used to find a distance between two coordinates
i = i+1;
end
i=1;
p2 = 101.52371;
for p1=3.682043:-0.5:2.227804
GtoJ(i) = distance(p1,p2,a5,b5); %% this function used to find a distance between two coordinates
i = i+1;
end
% -------------
I've put the results into two separate arrays AtoF and GtoJ and used the counter i for indexing them. You may have to pay special attention to the end points (it's not clear from your diagram whether they should be included) - and you may need to fine-tune the step size (0.5) for each loop to get the correct number of results which includes one near the end point.