Correct Magic Square to text file?
3 views (last 30 days)
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);
fileID = fopen('myfile.txt','w');
nbytes = fprintf(fileID,'%5d %5d %5d %5d\n',B);
Rik on 21 Jan 2022
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).
Image Analyst on 21 Jan 2022
% 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.