MATLAB: Function in for loop

for loopfunction

I want to create an vector. The vector needs to get created in a forloop, using a function. so what i want it to become: R=(R1, R2, R3… RN)
But the problem is, after the loop the vector is like (0 0 0 0 … RN) the part of my code that is important for this :
R=zeros(1,length(Numbers_used_P4))
for i=1:length(Numbers_used_P4)
CentreCircle(M,NumbersP4,x,y,d,i,P4_x,P4_y,xrel,yrel,R)
end
with the function
function [] = CentreCircle(M,NumbersP4,x,y,d,i,P4_x,P4_y,xrel,yrel,R)
if M(i)<1
Number=NumbersP4(i)
x_4(i)=x(Number)
y_4(i)=y(Number)
dx(i)=xrel(Number)
dy(i)=yrel(Number)
d_4(i)=d(Number)
Der(i)=dy(i)/dx(i)
A(i)=1-M(i).^2
B(i)=2*(M(i)^2)*d_4(i) ;
C(i)=-M(i)^2*d_4(i)^2 ;
D(i)=sqrt(B(i)^2-4*A(i)*C(i)) ;
a_1(i)=(-B(i)+D(i))/(2*A(i)) ;
a_2(i)=(-B(i)-D(i))/(2*A(i)) ;
dc(i)=(a_1(i)+a_2(i))/2 ;
ddx(i)=(dc(i)/d_4(i))*dx(i) ;
ddy(i)=(dc(i)/d_4(i))*dy(i) ;
ddx_A_1(i)=(a_1(i)/d_4(i))*dx(i);
ddy_A_1(i)=(a_1(i)/d_4(i))*dy(i);
ddx_A_2(i)=(a_2(i)/d_4(i))*dx(i);
ddy_A_2(i)=(a_2(i)/d_4(i))*dy(i);
A_1_x(i) = P4_x+ddx_A_1(i)
A_1_y(i) = P4_y+ddy_A_1(i)
A_2_x(i) = P4_x+ddx_A_2(i)
A_2_y(i) = P4_y+ddy_A_2(i)
C_x(i)=P4_x+ddx(i) ;
C_y(i)=P4_y+ddy(i) ;
else
M_inv(i)=1/M(i)
Number=NumbersP4(i)
x_4(i)=x(Number)
y_4(i)=y(Number)
dx(i)=xrel(Number)
dy(i)=yrel(Number)
d_4(i)=d(Number)
Der(i)=dy(i)/dx(i)
A(i)=1-M_inv(i).^2
B(i)=2*(M_inv(i)^2)*d_4(i) ;
C(i)=-M_inv(i)^2*d_4(i)^2 ;
D(i)=sqrt(B(i)^2-4*A(i)*C(i)) ;
a_1(i)=(-B(i)+D(i))/(2*A(i)) ;
a_2(i)=(-B(i)-D(i))/(2*A(i)) ;
dc(i)=(a_1(i)+a_2(i))/2 ;
ddx(i)=(dc(i)/d_4(i))*dx(i) ;
ddy(i)=(dc(i)/d_4(i))*dy(i) ;
ddx_A_1(i)=(a_1(i)/d_4(i))*dx(i);
ddy_A_1(i)=(a_1(i)/d_4(i))*dy(i);
ddx_A_2(i)=(a_2(i)/d_4(i))*dx(i);
ddy_A_2(i)=(a_2(i)/d_4(i))*dy(i);
A_1_x(i) = x_4(i)+ddx_A_1(i)
A_1_y(i) = y_4(i)+ddy_A_1(i)
A_2_x(i) = x_4(i)+ddx_A_2(i)
A_2_y(i) = y_4(i)+ddy_A_2(i)
C_x(i)= x_4(i)+ddx(i) ;
C_y(i)= y_4(i)+ddy(i) ;
end
R(i)=abs(a_1(i)-dc(i))
R2(i)=(abs(a_1(i))+abs(a_2(i)))/2
I've tried several things but I just don't get why it works like this

Best Answer

You need to output something from your function, most likely your want R and R1, e.g.
function [R,R1] = CentreCircle(M,NumbersP4,x,y,d,i,P4_x,P4_y,xrel,yrel,R)
and then in the loop you will need to allocate one or both of those outputs to some matrix, e.g.:
R = zeros(1,numel(Numbers_used_P4))
for k=1:numel(Numbers_used_P4)
R(k) = CentreCircle(M,NumbersP4,x,y,d,k,P4_x,P4_y,xrel,yrel,R);
end
As you did not describe how your algorithm works, you will have to figure out the exact outputs that you need.