using fopen and fscanf in loop
29 views (last 30 days)
Show older comments
Hi everybody I have 1000 output files with time and acceleration. accel(1).out to accel(1000).out I have to remove all time columns from all files and save the maximum accelerations in a matrix.
this simple code can do it for 3 files but when I do it in loop it gives error, probably the problem is with fscanf part, any suggestion???
i=1; j=2; k=3;
fid(i) = fopen(['accel(',num2str(i),').out'],'r');
fid(j) = fopen(['accel(',num2str(j),').out'],'r');
fid(k) = fopen(['accel(',num2str(k),').out'],'r');
[a] = fscanf(fid(i), '%f' , [2 inf]);
[b] = fscanf(fid(j), '%f' , [2 inf]);
[c] = fscanf(fid(k), '%f' , [2 inf]);
fclose(fid(i));
fclose(fid(j));
fclose(fid(k));
a(1,:) = [];
b(1,:) = [];
c(1,:) = [];
acc_matrix = [a' b' c']
====================================
the way i do it in loop which is wrong !!!
ii = 1:3;
fid(ii) = fopen(['accel(',num2str(ii),').out'],'r');
[a(ii)] = fscanf(fid(ii), '%f' , [2 inf]);
fclose(fid(ii))
many thanks
0 Comments
Accepted Answer
Image Analyst
on 22 Aug 2013
You need to have the word "for" before the "ii=1:3", and you don't need the semicolon at the end of that line, and you need an "end" at the end of the loop. Then you're reading a bunch of values into just one element, a(ii), of the array. That won't work. YOu'd need to preallocate a and read the values into a row, a(ii, :) - note the comma and semicolon.
1 Comment
Image Analyst
on 23 Aug 2013
Edited: Image Analyst
on 23 Aug 2013
Regarding your "Answer" below...I think that all your data is not 3 elements long. Try
pre_matrix = zeros(3000,3);
for ii = 1:3000
fid(ii) = fopen(['disp(',num2str(ii),').out'],'r');
a = fscanf(fid(ii), '%f' , [2 inf]);
size(a);
if size(a) == 3
pre_matrix(ii,:) = a;
end
fclose(fid(ii))
end
Even so, that is horrible, non-robust code. For example you don't even check if the file exists before you try to call fscanf(), you're making an array of file ID's when there is no need to do so, etc.
More Answers (1)
reza
on 23 Aug 2013
Edited: reza
on 23 Aug 2013
3 Comments
Image Analyst
on 23 Aug 2013
As another example of why this code is not robust, you're putting all your data into one row, the ii'th row. But you have only 3 columns because that's how you preallocated pre_matrix. Are you sure that each file you are reading has only 3 numbers in it? No, you didn't. Robust code would check for that, otherwise you'll throw an exception. Robust code would also use fullfile and sprintf to build up the filename. Robust code doesn't use disp() to create a string for use as a variable. Etc. I think you might want to read http://www.mathworks.com/matlabcentral/answers/8026-best-way-s-to-master-matlab
See Also
Categories
Find more on Data Type Conversion 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!