Saving matrices from workspace to textfile

5 次查看(过去 30 天)
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

回答(1 个)

Andrew Newell
Andrew Newell 2014-4-11
编辑:Andrew Newell 2014-4-11
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 个评论
Bob
Bob 2014-4-11
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 2014-4-11
编辑:Andrew Newell 2014-4-11
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by