Output variables and text to .txt file

7 views (last 30 days)
Matthew Piccolo
Matthew Piccolo on 15 Apr 2017
Answered: Nick on 16 Apr 2017
I am trying to output text and their related variables to a .txt file. I want the file to look like:
Mean = XXX.YY
Median = XXX.YY
Mode = XXX.YY
Var = XXX.YY
Stdev = XXX.YY
Min = XXX.YY
Max = XXX.YY
Count = XXXXXX
With all except count to have 2 decimal places, the equal signs to be vertically aligned, and the decimal points to be vertically aligned. I do not have the formatting down, and I thought I had the output file script written correctly. Here is what I have:
x_count = 32;
x_max = 150;
x_mean = 36.7500;
x_median = 18.5000;
x_min = 0;
x_mode = [4,7,8,15];
x_std = 39.4018;
x_var = 1.5525e+03;
C = cell(8,2);
C{1,1} = 'Mean=';
C{1,2} = x_mean;
C{2,1} = 'Median=';
C{2,2} = x_median;
C{3,1} = 'Mode=';
C{3,2} = x_mode;
C{4,1} = 'Var=';
C{4,2} = x_var;
C{5,1} = 'Stdev=';
C{5,2} = x_std;
C{6,1} = 'Min=';
C{6,2} = x_min;
C{7,1} = 'Max=';
C{7,2} = x_max;
C{8,1} = 'Count=';
C{8,2} = x_count;
fileID = fopen('exp.txt','w');
fprintf(fileID,'%6.2f %12.8f\r\n',C);
fclose(fileID);
type exp.txt
I'm using a cell to basically have an array with both text and numbers, but the function to print these doesn't work with cells, so now I'm assuming I need an entirely new way to do this. If it is more efficient and possible to align the equal signs and decimal points, all the better.
  2 Comments
per isakson
per isakson on 15 Apr 2017
Edited: per isakson on 15 Apr 2017
  • Matlab is column major, i.e. the columns of C are printed one after another.
  • x_mode is a vector and thus doesn't match the format specifier
  • "... 2 decimal places ..." &nbsp but you have specified eight
  • It is easier to print this data to a file using a for-loop
Matthew Piccolo
Matthew Piccolo on 16 Apr 2017
I found the printing code specifically on another page on this website. I wasn't really sure of what every parameter meant, and was hoping someone could explain them. It was literally just a copy-paste that I was hoping to figure out along the way.

Sign in to comment.

Accepted Answer

Nick
Nick on 16 Apr 2017
Hi, take a look at this from the file exchange
so to write to the cell array to text file you would give the filename and the cell to write as arguments so:
dmlcell('exp.txt',C);

More Answers (0)

Categories

Find more on Tables 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!