Export to a fixed width text file

조회 수: 29 (최근 30일)
Jesse Hutchinson
Jesse Hutchinson 2013년 5월 28일
Hi. I have a fairly simple problem, but haven't figured out how to solve it.
I would like to convert a cell array to a text file with fixed width columns. For example, the first row might contain a mixture of strings and numbers:
's09' 1111222003 321 'P' 'ehz'
and I want to have five spaces between the first and second columns, seven spaces between the second and third, and 3 spaces between the third and fourth. The reason for this is because I am converting the data into a very finicky format.
Thanks for any help in advance.

채택된 답변

Jonathan Sullivan
Jonathan Sullivan 2013년 5월 28일
편집: Jonathan Sullivan 2013년 5월 28일
Use sprintf / fprintf
Here is an example of making everything 16 characters wide:
A={'s09' 1111222003 321 'P' 'ehz';'z09' 1011222003 321 'O' 'edz'};
A=cellfun(@num2str,A,'Un',false)
for ii = 1:size(A,1);
B{ii} = sprintf([repmat('%16s',1,size(A,2)) '\n'],A{ii,:});
end
B = cat(2,B{:})
The number (16) between the % and the s determines the width that it will print out the entry. For more information type
help sprintf
doc sprintf
or
help fprintf
doc fprintf
  댓글 수: 1
Jesse Hutchinson
Jesse Hutchinson 2013년 5월 28일
편집: Jesse Hutchinson 2013년 5월 28일
Thanks a bunch. I ended up choosing to keep the string and number data separate and used fprintf to generate my text file. This is the final bit of code:
[nrows,ncols] = size(pickcat);
filename = 'test.arrival';
fid = fopen(filename,'w');
for row=1:nrows
fprintf(fid,'%-6s %17.5f %8d %8d %8d %8d %-8s %-8s %-1s %6.3f %7.2f %7.2f %7.2f %7.2f %7.2f %7.3f %10.1f %7.2f %7.2f %-1s %-2s %10.5g %-1s %-15s %8d %17.5f\n',pickcat{row,:});
end
fclose(fid);
As you can see, I had quite a complex data set! Thanks so much for the help.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Iman Ansari
Iman Ansari 2013년 5월 28일
A={'s09' 1111222003 321 'P' 'ehz';'z09' 1011222003 321 'O' 'edz'};
A=cellfun(@num2str,A,'Un',false)
B=strcat(A(:,1),{' '},A(:,2),{' '},A(:,3),{' '},A(:,4),A(:,5))
  댓글 수: 2
Jesse Hutchinson
Jesse Hutchinson 2013년 5월 28일
That seems to work great. Unfortunately, the character length on the values in some of my columns vary.
I am trying to think of a way to have a set column width (say, eight spaces for the first column) even though the value written within the first column may vary between 3 and 5 characters, while the rest need to be blank.
Iman Ansari
Iman Ansari 2013년 5월 28일
편집: Iman Ansari 2013년 5월 28일
A={'s09' 1111222003 321 'P' 'ehz';'ere09' 11222003 31 'O' 'dz'};
for i=1:2
B(i,:)=sprintf('%-5s %-12d %-3d %-s %-3s',A{i,1},A{i,2},A{i,3},A{i,4},A{i,5})
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by