MATLAB: Export to a fixed width text file

cell arraysexportfixed width

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.

Best Answer

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
Related Question