mean and variance of numbers read from a txt

조회 수: 7 (최근 30일)
NIMA RAHMANI MEHDIABADI
NIMA RAHMANI MEHDIABADI 2019년 5월 22일
편집: Jyotish Kumar 2019년 5월 29일
so i have text that has numbers 1,2,3,4,...,19,20
and i like to take the mean and varience of the numbers, how can i do it?
in_file = fopen( 'C:\Users\User\Desktop\LabWeek10\data.txt', 'r');
[x,count] = fscanf(in_file, ' %f',[1,inf])
mean = sum(x)/count;
fclose(in_file);
but it returns wrong mean.
  댓글 수: 1
dpb
dpb 2019년 5월 22일
Don't use mean as a variable name; that aliases the builtin function of the same name.
Presuming the file can be read by the given format statement (something we have no way to know is true or not), then
meanx=mean(x);
varx=var(x);
does the deed more neatly and if the data are capable of being interpreted correctly should return the same value....of course, it will not do so if you have previously executed the previous code snippet and not yet executed a clear mean command to get rid of the alias.
We would have to see the file to have any definitive answer.

댓글을 달려면 로그인하십시오.

답변 (1개)

Jyotish Kumar
Jyotish Kumar 2019년 5월 29일
편집: Jyotish Kumar 2019년 5월 29일
Hi,
You are using .txt file which has numbers like 1,2,3, 4,...,19,20. That is comma separated numbers and in order to calculate mean and variance, you need to first skip comma. Here I have created one .txt file which has numbers with comma separated.
str = '78,72,64,66,49';
fileID = fopen('temperature.txt','w');
fprintf(fileID,'%s',str);
fclose(fileID);
Now, execute code skipping comma (The extended ASCII code 44 represents the comma sign).
in_file = fopen( 'temperature.txt', 'r');
comma = char(44);
[x,count] = fscanf(in_file, [' %f' comma],[1,inf])
mean = sum(x)/count;
fclose(in_file);
x =
78 72 64 66 49
count =
5
mean=
65.8000
Now you can similarly calculate your variance.
Hope it helps to solve your problem.

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by