Save data to text file. Two vectors, a konstant and a text

7 views (last 30 days)
Hello everyone!
I am trying to save some data to a .txt file, and i am having a bit of a trouble for it to save correct.
i have the following code:
P';
F';
fprintf(fid, [ header1 ' ' header2 ' ' header3 ' ' header4 '\r\n']);
fprintf(fid, '%f %f %f %f \r\n', [P F L S]');
fclose(fid);
P and F is a vector of 1xn length, while L and S only has one value.
I need it to save it to a .txt file, that i can read again. Havn't got to the load part yet, since i want the file to save this data correct.
Something like this:
F P L S
1 1 5 text
2 2
3 3
any ideas what would make this work?
Thanks in advance :)

Answers (1)

dpb
dpb on 26 Apr 2015
Edited: dpb on 26 Apr 2015
You can't concatenate the numeric and string values in the argument list via [] nor the varying size of the first output line and the rest other than in a cell array and Matlab i/o functions aren't extended to handle cell arrays automagically. So it'd be simpler to write the code specific to the situation instead of trying to over-generalize. (Like the holy grail of vectorization, generalization is good, but sometimes can try to carry it beyond the realm of the practical).
First, since you want a header and have some text, decide on a field width. If the data are as shown simply a set of small integers, that's pretty simple; we'll just assume a one-character name as you've shown and a set of positive integers <100 so a field width of 3 will ensure at least one blank.
fid=fopen('yourfile');
% First just write the header since it's so simple as fixed string
fprintf(fid,' P F L S\n');
fmt=[repmat(1,3,'%3d') ' %s\n']); % format for first line included text
fprintf(fid,fmt,P(1),F(1),L,S) % write first row
fmt=repmat(1,2,'%3d') \n'); % format for remainder of file
fprintf(fid,fmt,[P(2:end).' F(2:end).'].') % NB: .' on array to output row order
fid=fclose(fid);
Since the two variables are vectors and you're writing a fixed number of columns, you don't need any count of the length. To write a general square 2D array you would count the number of columns and write the repmat statement argument to match; it's why I used the form here as demonstration even though writing a specifc number of repeated formats is easy enough here, in the general case it gets totally impractical. The idea is simple but until you've seen it, it isn't that obvious to build a dynamic format string this way. (Steven Lord of TMW showed me this "trick" years ago...it's just one of those things that comes along with Matlab since C from which the ML i/o is derived chose to not use a form for format control strings that allows for repeat field counts within the string a la Fortran FORMAT)

Community Treasure Hunt

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

Start Hunting!