Handle a .csv file and save folder path
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi I've got this simple matlab script :
clear all;
close all;
clc;
outFileName = [‘fileTest.csv'];
fid = fopen(outFileName, 'w');
fprintf(fid,'Colonna1, Colonna2, Colonna3, Colonna4\n');
mattiz = zeros(1000,4);
for i=1:1:1000
matrice(i,:) = [i i i i];
fid = fopen(outFileName, 'a');
fprintf(fid,'%d, ', matrice(i,1));
fprintf(fid,'%d, ', matrice(i,2));
fprintf(fid,'%d, ', matrice(i,3));
fprintf(fid,'%d,\n', matrice(i,4));
fclose(fid);
end
I would save my fileTest in the desktop, I'm running Matlab 2013b on a MacBook Pro, how should I write the path? With backslash or not? Thank you.
0 Kommentare
Antworten (2)
Geoff Hayes
am 17 Jun. 2014
Bearbeitet: Geoff Hayes
am 17 Jun. 2014
If you want to save the file to a particular directory (i.e. the desktop) then you could do something like the following
directory = '/Users/geoff/Desktop';
filename = 'fileTest.csv';
fileDest = fullfile(directory,filename);
fid = fopen(fileDest, 'w');
if fid>0
% do your work
for i=1:1:1000
% stuff
end
% close the file
fclose(fid);
end
One thing you may want to consider in your code is to remove the repetitive opening of the file on each iteration of the loop
fid = fopen(outFileName, 'a');
While this is "allowed", there is no corresponding fclose(fid) for each fopen so you have multiple file descriptors for the same file which may lead to difficulty trying to open that file in another application - you will have to close all file descriptors or shut down MATLAB in order to view that file.
Since you already have the file descriptor from when you opened the file, then just re-use that one and don't try to get another.
And all iterations have been completed, close the file with fclose(fid), like in the sample code of this answer.
Try the above and see what happens!
EDIT check out fileDest once this variable has been initialized and observe the effect of fullfile (it will add the slash for you).
0 Kommentare
Ken Atwell
am 17 Jun. 2014
Since you are ultimately creating a CSV file, you do this much more directly using the table data type:
M = zeros(1000,4);
% Do math
T = array2table(M, 'VariableNames', {'Colonna1', 'Colonna2', 'Colonna3', 'Colonna4'});
writetable(T, '/Users/geoff/Desktop/output.csv')
Siehe auch
Kategorien
Mehr zu File Operations 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!