% a more efficient solution to the matlab_tutorial 2 example % on random numbers; this will work quickly with values of n % as large as several million. The for-loop solution given in % the tutorial is MUCH slower. It is generally best to avoid % loops in MATLAB (if possible) if working with big arrays n=input('enter value of n: '); % if user enters no value, use n=2000 if(isempty(n)) n=2000;end % generate n values of x and y, uniformly distributed on [0,1] x=rand(n,1); y=rand(n,1); %( caution! rand(2000) generates 2000x2000 array - see help rand) % find indices of those x,y satisfying x^2+y^2<1, y>x (see help find) indices=find(x.^2+y.^2<1 & y>x); nused=length(indices); plot(x(indices),y(indices),'k.') set(gca, 'FontSize',16) title([num2str(nused) ' random pairs'])