MATLAB Answers

How can i assign certain length for each column of exported text file?

조회 수: 1(최근 30일)
Joseph 18 Jul 2019
Commented: Joseph 19 Jul 2019
I am trying to write a 8680*18 cell array in to a text file. But i need to assign certain defferent lenght for elements in each column (i.e. all elements in first have 3 characters and all elements in the second column have 12 characters, etc). can anyone help?
Thank you

  댓글 수: 0

로그인 to comment.

채택된 답변

Walter Roberson
Walter Roberson 19 Jul 2019
None of the Mathworks supplied tools for writing out matrices support that, so you will need to construct it yourself.
col_widths = [3 12 etc];
fmt_cell = [sprintfc('%%%ds', col_widths), '\n'];
fmt = [fmt_cell{:}];
your_cell_transpose = your_cell.';
fid = fopen('YourFile.txt', 'wt');
fprintf(fid, fmt, your_cell_transpose{:});

  댓글 수: 3

Joseph 19 Jul 2019
Thank you Walter for your answer.
I tried below script and worked for me.
import the cell array using fprintf. Open a file that you can write to named celldata.dat. Define formatSpec using the format specifiers to describe the pattern of the data in the file. Typical format specifiers include '%s'for a character vector, '%d' for an integer, or '%f' for a floating-point number. Separate each format specifier with a space to indicate a space delimiter for the output file. Include a newline character at the end of each row of data ('\n').
fileID = fopen('celldata.dat','w');
formatSpec = '%s %d %2.1f %s\n';
Determine the size of C and export one row of data at a time using the fprintf function. Then close the file. fprintf writes a space-delimited file.
[nrows,ncols] = size(C);
for row = 1:nrows
Walter Roberson
Walter Roberson 19 Jul 2019
Ah, that is for mixed datatype; your question sort of implied everything was char.
Your format would have to be touched up for fixed width, such as
formatSpec = '%3s %12d %2.1f %s\n';
Note this is for right-justified in field; if you want left-justified, use a negative width, such as %-3s
Joseph 19 Jul 2019
Thanks Walter. You are always helpful.

로그인 to comment.

More Answers (0)

이 질문에 답변하려면 로그인을(를) 수행하십시오.

Translated by