using fopen and fscanf in loop
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
3 commentaires
Image Analyst
le 23 Août 2013
Is this an "Answer"???
Image Analyst
le 23 Août 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
Catégories
En savoir plus sur Variables dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!