Saving matrices from workspace to textfile
1 回表示 (過去 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!