MATLAB: Please help me to rewrite the following codes

code generation

%% Calculation of phi and f
a11 = ai(1);
a12 = ((ai(1)*ai(2))^0.5)*(1-bin_PR(1,2));
a13 = ((ai(1)*ai(3))^0.5).*(1-bin_PR(1,3));
a21 = a12;
a22 = ai(2);
a23 = ((ai(2)*ai(3))^0.5)*(1-bin_PR(2,3));
a31 = a13;
a32 = a23;
a33 = ai(3);
sum_xa(1) = x(1)*a11 + x(2)*a12 +x(3)*a13;
sum_xa(2) = x(1)*a21 + x(2)*a22 +x(3)*a23;
sum_xa(3) = x(1)*a31 + x(2)*a32 +x(3)*a33;
sum_ya(1) = y(1)*a11 + y(2)*a12 +y(3)*a13;
sum_ya(2) = y(1)*a21 + y(2)*a22 +y(3)*a23;
sum_ya(3) = y(1)*a31 + y(2)*a32 +y(3)*a33;
phi_L=exp((bi./b_L).*(ZLt-1)-log(ZLt-B_L)-(A_L./(B_L.*(-2*sqrt(2)))).*(log((ZLt+(1-sqrt(2)).*B_L)/(ZLt+(1+sqrt(2)).*B_L)))*((2*sum_xa/a_L)-(bi./b_L)));
phi_G=exp((bi./b_G).*(ZGt-1)-log(ZGt-B_G)-(A_G./(B_G.*(-2*sqrt(2)))).*(log((ZGt+(1-sqrt(2)).*B_G)/(ZGt+(1+sqrt(2)).*B_G)))*((2*sum_ya/a_G)-(bi./b_G)));
------------------------------------
-----------------------------------------
I want to write the above coding like this (below one):
for i=1:3
for j=1:3
el_L(i,j)=x(i).*x(j)*((ai(i).*ai(j)).^0.5).*(1-bin_PR(i,j));
el_G(i,j)=y(i).*y(j)*((ai(i).*ai(j)).^0.5).*(1-bin_PR(i,j));
end
end
a_L=sum(el_L(:));
b_L=sum(x.*bi);

Best Answer

YOu need not to use a loop for your code. YOu can achieve it by simple matrix multiplication. Check the below code.
a11 = ai(1);
a12 = ((ai(1)*ai(2))^0.5)*(1-bin_PR(1,2));
a13 = ((ai(1)*ai(3))^0.5).*(1-bin_PR(1,3));
a21 = a12;
a22 = ai(2);
a23 = ((ai(2)*ai(3))^0.5)*(1-bin_PR(2,3));
a31 = a13;
a32 = a23;
a33 = ai(3);
A = [a11 a12 a13 ; a21 a22 a23;a31 a32 a33] ;
b1 = x ; % this should be a 3X1 array

b2 = y ; % this should be a 3X1 array
sum_xa = A*b1 ;
sum_ya = A*b2 ;
phi_L=exp((bi./b_L).*(ZLt-1)-log(ZLt-B_L)-(A_L./(B_L.*(-2*sqrt(2)))).*(log((ZLt+(1-sqrt(2)).*B_L)/(ZLt+(1+sqrt(2)).*B_L)))*((2*sum_xa/a_L)-(bi./b_L)));
phi_G=exp((bi./b_G).*(ZGt-1)-log(ZGt-B_G)-(A_G./(B_G.*(-2*sqrt(2)))).*(log((ZGt+(1-sqrt(2)).*B_G)/(ZGt+(1+sqrt(2)).*B_G)))*((2*sum_ya/a_G)-(bi./b_G)));
Related Question