Save a double array to a text file

99 ビュー (過去 30 日間)
AP
AP 2021 年 4 月 3 日
編集済み: Image Analyst 2021 年 4 月 4 日
Hello,
I have a double array that looks like this:
0.3764 0.6801 0.1926 -0.1987 0.3531
0.0313 -0.2461 0.0218 0.0299 -0.3008
-0.1811 -0.1639 -0.0698 0.0397 -0.2341
0.3469 0.3152 6.1030 -0.3613 0.3749
-0.5791 -0.2253 -0.3613 6.1030 -0.2178
I want to save this to a text file so that the output text file looks exactly like the above data
I tried the dlmwrite command but I do not want to specify precision, and the examples I have found create a file with ' ; ' in between which is not something I want.

採用された回答

Image Analyst
Image Analyst 2021 年 4 月 3 日
編集済み: Image Analyst 2021 年 4 月 4 日
Try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format short g;
format compact;
fontSize = 18;
fprintf('Beginning to run %s.m ...\n', mfilename);
fileName = 'deleteme.txt';
fid = fopen(fileName, 'wt');
m = [
0.3764 0.6801 0.1926 -0.1987 0.3531
0.0313 -0.2461 0.0218 0.0299 -0.3008
-0.1811 -0.1639 -0.0698 0.0397 -0.2341
0.3469 0.3152 6.1030 -0.3613 0.3749
-0.5791 -0.2253 -0.3613 6.1030 -0.2178
]
[rows, columns] = size(m);
for row = 1 : rows
for col = 1 : columns
fprintf(fid, '%f ', m(row, col));
end
fprintf(fid, '\n');
end
fclose(fid);
winopen(fileName); % Open in Notepad or Wordpad
  1 件のコメント
AP
AP 2021 年 4 月 3 日
Great! This worked the way I wanted.Thank you!

サインインしてコメントする。

その他の回答 (2 件)

the cyclist
the cyclist 2021 年 4 月 3 日
Regardless of what is displayed to the MATLAB command window (in your case, the default format, it seems), an array of type double is storing 64-bit, double-precision floating-point values.
So, I don't believe it is possible for you to achieve both of the following things you want:
  • write that exact format
  • do not specify the precision (i.e. format)
Also, all functions that write output have to choose some delimiter by default. Usually, that delimiter can be chosen to be something else.
The writematrix command might do what you want?
  1 件のコメント
AP
AP 2021 年 4 月 3 日
Thank you!

サインインしてコメントする。


madhan ravi
madhan ravi 2021 年 4 月 3 日
  1 件のコメント
AP
AP 2021 年 4 月 3 日
Thank you!

サインインしてコメントする。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by