fopen, fscanf, nested for loops

5 次查看(过去 30 天)
Check the file ID to determine if the file is available.
Only print message if file is not available.
Use nested for loops to read one water level value at a time into the lake_powell matrix.
lake_powell(month,year) = fscanf(fileID, '%f', 1);.
Use mean to determine the average elevation of the water level for each year and the overall average for the four-year period over which the data were collected. Print the yearly average vector and the overall average with labels as shown below.
%*****CONSTANT*****
fileID= fopen('lake_powell.txt');
lake_powell = fscanf(fileID, '%f', 1);
if exist('lake_powell.txt', 'file')
% File exists. Do stuff....
%*****INPUT*****
% read data file
years = ( 2013:1:2016 );
fprintf('\nLake Powell Water Levels (in feet)\n');
% if file doesn't exist
if exist('lake_powell.txt', 'file')
% File exists. Do stuff....
% print title and year column headings.
for i=1:length(years)
fprintf('%6.0d\t', years(i));
end
% print contents of lake_powell
for i=1:size(lake_powell,1)
fprintf('\n')
for j=1:size(lake_powell,2)
fprintf('%.2f\t',lake_powell(i,j));
end
end
fprintf('\n');
% PART B: use mean to determine average elevation
fprintf('\n');
mean_each_year = mean(lake_powell,1);
fprintf('\n Average for Each Year (in feet)\n');
for i=1:length(years)
fprintf('%9.0d',years(i));
fprintf('\n');
for i=1:length(mean_each_year)
fprintf('%10.2f',mean_each_year(i));
end
end
overall_mean= mean(mean_each_year);
fprintf('\n Overall average:%10.2f feet',overall_mean);
else
disp('File not found');
end
else
disp('File not found');
end
I'm supposed to have an output of
Average for Each Year (in feet)
2013 2014 2015 2016
3579.90 3585.70 3600.78 3602.36
Overall average: 3592.18 feet
but im getting
Average for Each Year (in feet)
2013
3594.38 2014
3594.38 2015
3594.38 2016
3594.38
Overall average: 3594.38 feetImage 3-7-19 at 9.37 PM.jpg

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by