mean and variance of numbers read from a txt

9 ビュー (過去 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 Center および File ExchangeText Data Preparation についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by