mean and variance of numbers read from a txt

9 Ansichten (letzte 30 Tage)
NIMA RAHMANI MEHDIABADI
NIMA RAHMANI MEHDIABADI am 22 Mai 2019
Bearbeitet: Jyotish Kumar am 29 Mai 2019
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 Kommentar
dpb
dpb am 22 Mai 2019
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Jyotish Kumar
Jyotish Kumar am 29 Mai 2019
Bearbeitet: Jyotish Kumar am 29 Mai 2019
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.

Tags

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by