For loop not working through matrix

17 Ansichten (letzte 30 Tage)
Grace Pooley
Grace Pooley am 1 Nov. 2021
Bearbeitet: DGM am 1 Nov. 2021
I am trying to pull the data from each row of the entire 100x2 int16 matrix of "cr" and print in my file 'conc.dat'. However, only one row is being printed, it does not seem like my for loop is going through the entire matrix. Can someone help me figure out why and how to fix this issue?
for k = 1:length(cr);
row = cr(k,:);
conc = counts(row(:,1));
fileID = fopen('conc.dat','w');
fprintf(fileID,'\n');
fprintf(fileID,'%12.f\n',conc);
fclose(fileID)
end

Akzeptierte Antwort

DGM
DGM am 1 Nov. 2021
Bearbeitet: DGM am 1 Nov. 2021
You're overwriting the file every single time you write a line. That's the difference between opening the file with 'w' permissions and 'a' (write-append) permissions.
There's no need to open and close the file every single time anyway. Just move that outside the loop.
cr = [1:10; 11:20].'
counts = 101:110;
fileID = fopen('conc.dat','w');
for k = 1:length(cr)
row = cr(k,:);
conc = counts(row(:,1));
fprintf(fileID,'\n');
fprintf(fileID,'%12.f\n',conc);
end
fclose(fileID);
  1 Kommentar
Grace Pooley
Grace Pooley am 1 Nov. 2021
Magic, thank you for the thorough explanation!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by