sequential files(write, read ,append)?
5 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Paulo Silva
on 20 Apr 2011
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 Comments
Paulo Silva
on 20 Apr 2011
yes they are variables, choose the name that best describes what they are for and avoid using the same names as matlab functions.
More Answers (0)
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!