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
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!