writing maxtrix into a txt file

2 views (last 30 days)
Andy
Andy on 17 Jan 2012
I am trying to write a maxtrix into a txt file which contains other information, so i am wondering how i would go about this? could i use dlmwrite, will this write everything in the same file as my other information? Thanks.
p.s. right now i am writing every number in one by one with a nested loop, takes a long time to do since i have a 24000X103 matrix, and also takes forever to open.

Accepted Answer

Walter Roberson
Walter Roberson on 17 Jan 2012
dlmwrite() cannot handle a mix of text and numbers. It can handle numbers alone, and it can handle text alone (when backed in to a corner.)
Are you just trying to append a matrix to an existing file? If so then:
thisfmt = [repmat('%g ', 1, size(YourMatrix,2)-1),, '%g\n'];
fid = fopen('YourExistingFile.txt', 'at');
printf(fid, thisfmt, YourMatrix .'); %transpose is critical!
fclose(fid)
Adjust the %g to whatever is appropriate.
  2 Comments
Andy
Andy on 17 Jan 2012
thanks, that worked, just one more question, is there a limit as to how far to the right the txt file can be written? i mean when matlab writes the matrix in, it stopped before it wrote all 24000 numbers in and went to the next line and then continued there
Walter Roberson
Walter Roberson on 17 Jan 2012
The above code will write 24000 rows each containing 103 columns -- "row major order".
Did you want to write by columns across rather than by rows?
thisfmt = [repmat('%g ', 1, size(YourMatrix,1)-1),, '%g\n'];
fid = fopen('YourExistingFile.txt', 'at');
printf(fid, thisfmt, YourMatrix); %NO transpose!
fclose(fid)

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!