Saving matrices from workspace to textfile

4 views (last 30 days)
Bob
Bob on 11 Apr 2014
Edited: Andrew Newell on 11 Apr 2014
I contain a matrix MAT_1 which is a matrix of size 400x3 containing symbolic variables.
I would like to accomplish the following
1) Save this MAT_1 from workspace to a .txt file. I tried the usual load save, and didnt help.
2) Also my MAT_1 since an array contains characters such as '[', ']' which I would like to replace by blank spaces. Generally I do think by replacing, but realized its annoying.
3)Also is it possible to add few lines of text before the MAT_1 is saved on the .txt file?
Could anyone help! Thanks

Answers (1)

Andrew Newell
Andrew Newell on 11 Apr 2014
Edited: Andrew Newell on 11 Apr 2014
Here is some code that will do that:
% Convert to cell array of strings
mc = arrayfun(@char,MAT_1,'UniformOutput',false);
mc = mc.';
% Create format string of appropriate size
fmt = [repmat('%s ',1,size(mc,1)),'\n'];
% Write to file
fid = fopen('myfile.txt','w');
fprintf(fid,'Here is one line of text. Repeat as needed.\n');
fprintf(fid,fmt,mc{:});
fclose(fid);
  2 Comments
Bob
Bob on 11 Apr 2014
I am not sure if it solves my question. Im sorry i am a noob, so in my example where do i insert the Mat_1 matrix? and which line corresponds to the replacing '[' by ' '(blank spaces)
thanks
Andrew Newell
Andrew Newell on 11 Apr 2014
Edited: Andrew Newell on 11 Apr 2014
My edit will answer your first question. As to the second question, the first command places each component of MAT_1 in its own component of a cell array. No brackets are produced this way.
A detailed explanation of what the first line does: char converts a symbolic object to a string, while arrayfun applies this conversion to each element of MAT_1. The next line makes sure that fprintf prints out the components in the right order (that was just trial and error). The format string looks like '%s %s %s\n' for a three-column matrix, but will also work for matrices of other sizes. I hope that helps.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!