MATLAB: Adding some changes and code rewriting

adding some changes and code rewriting

[EDIT: 20110628 00:13 CDT – reformat – WDR]
i have code and i would like to make some changes and add 2 conditions for these 3 random variables (c, gama, fi). i want to limit each of them in a specific zone and check the random number which is generated in every loop to not be duplicated also not be out of range.
these are conditions:
  • 2.7< fi <16.3
  • 450< c <800
  • 1.92< gama <1.98
and each of them must be check to not be repeating in every loop.
this is my code :
clear;
clc
B=1000;L=2000;Sc=1.1;Sq=1.1;Sgama=.8;
nsamples=10000;
for i=1:nsamples
C=normrnd(620,147.64);
gama=normrnd(1.96,0.02);
fi=normrnd(3.76,1.1034);
Nq=tan((pi/4)+(pi*fi/360))*tan((pi/4)+(pi*fi/360))*2.718^(pi*tan(fi*pi/180));
Nc=(Nq-1)*cot(fi*pi/180);
Ngama=2*(Nq+1)*tan(fi*pi/180);
qult(i)=(C*Nc*Sc)+(384*Nq*Sq)+(980*Ngama*Sgama);
end

Best Answer

clc
B=1000; L=2000; Sc=1.1; Sq=1.1; Sgama=.8;
nsamples=10000;
rmem = zeros(3,nsamples);
for i=1:nsamples
while true
C = normrnd(620,147.64);
if C<=450 || C >= 800 || ismember(C,rmem(1,1:K-1)); continue; end
gama = normrnd(1.96,0.02);
if gama <= 1.92 || gama >= 1.98 || ismember(gama,rmem(2,1:K-1)); continue; end
fi = normrnd(3.76,1.1034);
if fi <= 2.7 || fi >= 16.3 || ismember(fi,rmem(3,1:K-1)); continue; end
rmem(:,K) = [C; gama; fi];
break
end
Nq = tan((pi/4)+(pi*fi/360)) * tan((pi/4)+(pi*f/360)) * exp(pi*tan(fi*pi/180));
Nc = (Nq-1)*cot(fi*pi/180);
Ngama = 2*(Nq+1)*tan(fi*pi/180);
qult(K) = (C*Nc*Sc)+(384*Nq*Sq)+(980*Ngama*Sgama);
end
I am not clear as to why you want to check for duplicates: it isn't that duplicates are impossible, but they are relatively rare at 53 bit precision. In the 500000 normrnd(620,147.6) that I generated as a test, the two closest values were a good 2.9899638320785e-11 apart, which was 7 clear bits greater resolution than the largest value generated. I calculate that a 50% chance of a duplicate does not arise until slightly under 112 million samples.
If you eliminate the checks for duplicates or generate a few extra points and discard the duplicates and any extras afterwards, then the code can be made considerably more efficient.