- you can compute a format string for fprintf
- fprintf follows down columns first, not across rows first. So we transpose the data so the rows become columns that are processed and printed as rows
- fprintf() cannot handle struct or cell directly
- you cannot mix text and numeric in a single argument
- but if you create a cell array and if you use {:} notation on the cell array, it becomes as if you had given everything as individual arguments, like everything was written out separated by commas. So with this code arrangement you effectively put in a string argument that is the label, then you put in a numeric argument that is a row, then another string argument, and so on.
Export Struct (.repr = dat + lab) to Textfile while preserving labels
2 views (last 30 days)
Show older comments
Amanda Van Horne
on 16 Sep 2015
Edited: Amanda Van Horne
on 17 Sep 2015
I have a struct file that consists of a rather large dat file (11444x1000) and a file of labels (11444 x 1) that I'd like to export to a text file. Ideally it would read out so that each line consists of the label followed by the 1000 unit vector. I'm comfortable in python but relatively new to matlab so I'm unclear on what the right steps would be. I assume I need something like
fileID = fopen('output.txt','w');
fprintf(fileID,'%f %f\n',y);
% but here all of the online instructions are for individual variables rather than structures.
fclose(fileID);
0 Comments
Accepted Answer
Walter Roberson
on 16 Sep 2015
[nrow, ncol] = size(YourStruct.data);
data_cell = mat2cell(YourStruct.data, ones(1,nrow), ncol); %break by rows
labels_cell = YourStruct.labels(:);
maxlen = max( cellfun(@length, labels_cell) );
rowfmt = ['%-', sprintf('%d', maxlen), 's ', repmat('%9.5f ', 1, ncol-1), '%.5f\n'];
labeled_data_cell = [labels_cell, data_cell] .'; %transpose it!
fprintf(fid, rowfmt, labeled_data_cell{:});
There are a few tricks here:
You could go as far as calculating the field width on the numbers to align the decimal points (remember to allow for the negative sign if your values can be negative)
2 Comments
More Answers (0)
See Also
Categories
Find more on String Parsing 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!