I have a code that i am using over and over n times in a for loop, so i keep fprintfing about 10 lines onto the command window for every one of the n runs through this for loop. Sometimes the output is too long for the command window. Could someone maybe tell me how to have this output continually be posted to an excel file? The one problem i anticipate is that since it is a for loop printing different results after each run though the loop, i would need the different output to keep posting on different lines of the excel file.
1 Answer
You can either export it directly to excel:
excel_header={'header1','header2','header3'};
warning('off','MATLAB:xlswrite:AddSheet')
filename = 'testdata.xlsx';
xlswrite(filename,excel_header,'SheetName','A1:C1');
Note that you if your data has different length in each iteration, you can build the ranges dinamically (eg: a column of variable size):
excel_range_dynamic=['A1:A' num2str(data_length)];
Alternatively you can export your data to any .txt or .csv file (which can be later opened with excel):
%Save to txt file
fi=fopen('test.txt','w');
fprintf(fi,'%s \n',str1); %str1 is any string you have defined
fprintf(fi,'%s\n%s\n%s\n',str2{:}); %str2 is a cell containing several strings
fclose(fi);
You can read more about fprintf formats here.
5 Comments
Dimitris Boukosis
What inputs should I use to this code so matlab knows what to save? Thank you very much!
Carlos Borau
well, it depends on your data. Show me an example of what you print in each loop
Dimitris Boukosis
I should print a dynamic series of vectors (4-6 vectors), a number (result) for each vector and a total Distance.
Carlos Borau
Next time write a real example (with numbers-strings etc), I have to assume too many things... In any case: fprintf(fi,'%2.2f \t %2.2f \t %2.2f \t \n',M'); % assuming that M is a matrix where each row is one of your vectors, each of them have 3 elements (columns) fprintf(fi,'%2.2f \n',result_number); %assuming result is a float fprintf(fi,'%2.2f \n',distance); %assuming distance is a float Note that \n jumps to new lines, you can change it by \t to add tabs instead. Here you have format info: es.mathworks.com/help/matlab/matlab_prog/…
Dimitris Boukosis
Oh, I'm really sorry, but thanks it was really helpful!
fprintfto export to csv, which you can open in excel.