MATLAB: How to remove the zeros in the cells of a matrix

matrix without zeros

Say I have matrix like this
>> part
part =
16 0 0
1 29 0
2 25 0
3 32 0
4 30 0
5 26 0
6 28 0
7 27 0
8 22 31
9 18 0
10 21 0
11 24 0
12 19 0
13 23 0
14 17 0
15 20 0
16 0 0
and I would like to write this matrix to a csv file without the zeros

Best Answer

output_lines = regexprep(cellstr(num2str(part,',%d')), {',\s*0', '\s+', '^,'}, {',', '', ''})
fid = fopen('YourOutputFile.csv', 'wt');
fprintf(fid, '%s\n', output_lines{:});
fclose(fid);
You can change the %d to %g to include floating point numbers. However, if you change the %d to %f then the code would need to be changed.