Correct Magic Square to text file?

2 ビュー (過去 30 日間)
Neil Ogle
Neil Ogle 2022 年 1 月 21 日
コメント済み: Neil Ogle 2022 年 1 月 24 日
In the simple script below, why when I open myfile.txt is its composed of A and not B (the transpose of A), even though I asked for the latter in the last line
A = magic(4);
B=A';
fileID = fopen('myfile.txt','w');
nbytes = fprintf(fileID,'%5d %5d %5d %5d\n',B);
  1 件のコメント
Stephen23
Stephen23 2022 年 1 月 21 日
A much simpler way to save the matrix is to use WRITEMATRIX or DLMWRITE or similar.

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

回答 (2 件)

Rik
Rik 2022 年 1 月 21 日
Your file is written row by row, while Matlab will read the data in B column by column.
So while most people would not expect this behavior, it is actually the expected behaviour.
You will have to transpose the the array again (or use the original).
  1 件のコメント
Neil Ogle
Neil Ogle 2022 年 1 月 21 日
Thanks, Helpful

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


Image Analyst
Image Analyst 2022 年 1 月 21 日
Try this:
% Create matrix.
A = magic(5)
% Write it out to a text file.
filename = fullfile(pwd, 'A Magic 5.txt')
writematrix(A, filename, 'Delimiter', ' ');
% Verify by typing it to the command window.
type(filename)
%delete(filename)
  1 件のコメント
Neil Ogle
Neil Ogle 2022 年 1 月 24 日
Yes, good stuff

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

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by