In the first edition, because the formula contains: the Denominator entry: N (n-1), and the program does not determine the number of inputs, if only one or one of the input is not entered, there will be a situation other than 0
Based on this, the second edition is improved.
Code:
%script file: states.m% %Target:%The program first accumulates an unknown number (positive or 0), and then calculates the average and variance of the data set.% %Release History%Date Editor Description% ===== ========= ================% --Ten-4 +: +Bubble Source% 2015-10-4 21:56 bubble correction except for 0 (when only 0 or 1 numbers are entered)%Define variables:%% M--Enter the number of samples% Std_dev--variance of input sample% sum_x--the input sample and% SUM_X2--sum of squares of input samples% x--Input Sample Values% Xbar--average of input samples% % % %clear variable or directive CLC;%variable initialization n=0; sum_x=0; sum_x2=0;%read the first input value x=input ('Please enter the first number:');%While Loop whileX >=0%Cumulative N= n+1; Sum_x= sum_x +x; SUM_X2= Sum_x2 +x^2; %Read Next value x=input ('Please enter the next number:'); end%% Check if there is a sufficient number of input data if n < 2 data volume is insufficient disp (' requires minimum input data of 2 '); else%calculate variance and mean X_bar=sum_x/N; Std_dev=sqrt ((n*sum_x2-sum_x^2)/(N (n1)) ); %Output fprintf ('The total number of data you have entered is:%f\n', N); fprintf ('The average is:%f\n', X_bar); fprintf ('Variance is:%f\n', Std_dev); End % %
MATLAB calculates mean and variance using while loop (second edition)