MATLAB: Nested loops of different dimension without using “for loops”

nested loop bsxfun

Hi, I'm having a problem implementing my code:
reflectance=0.2;
tilt=18;
Lat=37.4;
phi_c=0;
n=1:365; %Days in a year
delta=23.45*sind(360*(n-81)/365);
h=11:-1:-12; %hours
beta=asind(cosd(Lat).*cosd(delta).*cosd(15.*h)+sind(Lat).*sind(delta))
phi_s=asind((cosd(delta).*sind(15.*h))./cosd(beta))
theta=acosd(cosd(beta).*cosd(phi_s-phi_c).*sind(tilt)+sind(beta).*cosd(tilt))
theta=theta'
I_bc=DNI*cosd(theta)
I_rc=GHI.*reflectance.*((1-cosd(tilt))./2)
I_dc=DHI.*((1+cosd(tilt))./2)
I_c=I_bc+I_dc+I_rc
Basically, I want to compute the calculations for each hour (24 in total) for each day n (365 days). DNI, GHI and DHI are 8760×1 values each (24*365=8760).
I was told earlier to implement the bsxfun function, which is useful for different dimensions. Here is my attempt, but it's still not right:
n=1:365;
delta=23.45*sind(360*(n-81)/365);
h=11:-1:-12;
beta=asind(cosd(Lat).*bsxfun(@plus,bsxfun(@times,cosd(delta),cosd(15.*h)'),(sind(Lat).*sind(delta))))
theta=acosd(cosd(beta).*cosd((asind((cosd(delta).*sind(15.*h))./cosd(beta)))-phi_c).*sind(tilt)+bsxfun(@times,sind(beta),cosd(tilt)))
theta=theta'
I_bc=bsxfun(@times,DNI,cosd(theta))
I_rc=GHI.*reflectance.*((1-cosd(tilt))./2)
I_dc=DHI.*((1+cosd(tilt))./2)
I_c=I_bc+I_dc+I_rc
Is there any chance someone can help me on this?

Best Answer

ct = cosd(tilt);
p1 = cosd(15.*h(:))*cosd(delta);
sb = bsxfun(@plus,cosd(Lat)*p1,sind(Lat)*sind(delta));
cb = cosd(asind(sb));
phi_s = asind(bsxfun(@rdivide,p1,cb));
costheta = cb.*cosd(phi_s-phi_c).*sind(tilt)+sb.*ct;
s = size(sb);
I_bc = reshape(DNI,s).*costheta;
I_rc = reshape(GHI,s)*reflectance*(1-ct)/2;
I_dc = reshape(DHI,s)*(1+ct)./2;
I_c = I_bc+I_dc+I_rc;
ADD
I_c_out = I_c(:);