MATLAB calculates mean and variance using while loop (second edition)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.