Reputation: 230
I have created a text file which contains integer values such as follows:
1
2
3
4
5
56
10
.. and so on
The idea is to find the average of these numbers. I have done below but for some reason I am getting multiple outputs:
fid = fopen('random.txt', 'r');
data = fscanf(fid, '%i',1 );
fclose(fid);
averageValues= 'Average ' + (sum(data)/length(data))
Upvotes: 0
Views: 1314
Reputation: 3148
No to all answers. If your .txt file only consists of numbers, just do
>> load file.txt
>> mean(ans)
Example:
>> system('cat test.txt')
1
4
4
6
ans =
0
>> load test.txt
>> mean(test)
ans =
3.75
Upvotes: 0
Reputation: 29064
data = textread('random.txt',%i);
mean_data = mean(data);
%i is used because you have integer values. If you have double values, change it to %d.
Upvotes: 0
Reputation: 3677
You can read all data in one line of code:
data=textread('d:\1.txt','%d');
datamean=mean(data)
Upvotes: 0
Reputation: 1105
That call to fscanf
will read only the first line of your file. You should place it in a loop to actually read every line, or simply use one of the followings
data = cell2mat(textscan(fid, '%d'));
data = dlmread('random.txt')
The error you get is also in the last line. In Matlab you can't convert doubles into strings in that way. The correct code is
avg = mean(data);
disp(['Average = ' num2str(avg)]);
Upvotes: 2