How can save to a matrix to txt file
2 次查看(过去 30 天)
显示 更早的评论
Hi ,
I have a matrix (1081x72) in txt file. And I opened it via Microsoft Excel and save it xls format. And, Read this matrix from xls.Then transposed it. I want to save this transposed matrix to txt file. But when I try to save this matrix , it isn't showed properly. These are my input and outfile and codes.
A = xlsread('armstrong-2002-v1_database.xls')
B = transpose(A);
dlmwrite('myFile.txt',B,'delimiter',' ');
0 个评论
回答(3 个)
Walter Roberson
2015-10-9
I checked the .xls file and I checked the .txt file, and I do not see anything obvious wrong. All of the numeric values are there.
None of the header information is written out, but when you use xlsread() the first output only reflects the numeric content so it would not be expected that the headers would be written out. If you want to write out the headers as well, you should be using the three-output version of xlsread() and writing out the third of them:
[num, txt, raw] = xlsread('armstrong-2002-v1_database.xls');
And then you have to write out raw
A difficulty with writing out raw is that dlmwrite() only handles pure numeric values. You need to do some transformations on it and write it out as text:
B = raw;
B(cellfun(@isnan,B)) = {'-'}; %do not make it blank or empty or you will have trouble reading the file back in
idx = cellfun(@(C) ~isempty(C) && isnumeric(C(1)), B);
B(idx) = cellfun(@(V) sprintf('%g',V), B(idx), 'Uniform', 0);
%notice we have not transposed yet
fid = fopen('myFile.txt', 'wt');
%here's a trick: when you fprintf, it takes values down columns instead of across
%across rows. Normally you deal with that by transposing your data before sending it
%to fprintf. But we already have it in transposed form, so we can send it directly.
fmt = [repmat('%s ', 1, size(B,1)-1), '%s\n'];
fprintf(fid, B{:});
fclose(fid);
4 个评论
Walter Roberson
2015-10-9
A = xlsread('armstrong-2002-v1_database.xls')
B = transpose(A);
dlmwrite('myFile.txt', B, 'delimiter',' ', 'newline', 'pc');
Stephen23
2015-10-9
编辑:Stephen23
2015-10-9
The problem is not the file or the code, the problem is the text editor that you are using. Microsoft Notepad is very poor at handling large text files and particularly with handling long text rows. It is also notorious for mismanaging newline characters.
It seems that Notepad cannot display your file properly.
When I open your file in Notepad++ (a much better text editor) it looks fine. and matches exactly the transposed .xls data. You should upgrade your text editor to something more robust than Microsoft's Notepad, such as Notepad++.
Here is your text file shown in Notepad++ without word wrapping:

and shown in Notepad++ with word wrapping:

另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!