sequential files(write, read ,append)?

조회 수: 14 (최근 30일)
Kyle
Kyle 2011년 4월 20일
I'm having trouble understanding why my program wont work. I'm given an array of numbers. This is what i should be getting
45 66 78 23 41 55 88 66 99 24 74 88 -these should be in a vertical column
The number of lines of the integers is 12.
The max number is 99 in line 9.
The min number is 23 in line 4.
Heres what i have:
fid1=fopen('hw9.txt','w');
for x=[45 66 78 23 41 55 88 66 99 24 74 88]
fprintf(fid1,'%g\n',x);
end
fclose(fid1);
fid1=fopen('hw9.txt','r');
[numbers count] = fscanf(fid1,'%d');
[value index]=max(x);
[value2 index2]=min(x);
fclose(fid1);
disp(numbers)
fprintf('The number of lines of intergers is %g.\n',count)
fprintf('The max number is %g in line %g.\n',value,count)
fprintf('The min number is %g in line %g.\n',value2,index2)
Is the max function counting most common numbers?

채택된 답변

Paulo Silva
Paulo Silva 2011년 4월 20일
Your code had some mistakes, here's the fixed code
%create the file and write values to it
fid1=fopen('hw9.txt','w');
for x=[45 66 78 23 41 55 88 66 99 24 74 88]
fprintf(fid1,'%g\n',x);
end
%the for loop writes every value to the file, last one is 88, x=88
fclose(fid1);
%read the values inside the file
fid1=fopen('hw9.txt','r');
[numbers count] = fscanf(fid1,'%d');
[value index]=max(numbers); %replaced x by numbers, x value is 88
[value2 index2]=min(numbers); %same as above
fclose(fid1);
disp(numbers)
fprintf('The number of lines of intergers is %g.\n',count)
%in the next line you had count instead of index (strange mistake)
fprintf('The max number is %g in line %g.\n',value,index)
fprintf('The min number is %g in line %g.\n',value2,index2)
The max function finds the maximum value of the vector, the min finds the minimum value of the vector.
One extra feature that you might want is
fprintf('Unique Values and the times they appear\n')
disp([unique(numbers), histc(numbers,unique(numbers))])
  댓글 수: 2
Kyle
Kyle 2011년 4월 20일
Oh i see what i forgot. Quick question though, are count and numbers considered matlab variables or can they be changed to say [x y]=fscanf(fid1,'%d');
Paulo Silva
Paulo Silva 2011년 4월 20일
yes they are variables, choose the name that best describes what they are for and avoid using the same names as matlab functions.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by