2

I want to write out some data to a text file in Matlab but I am having problems. I want the file to look like this

'AnatomicImage:13'
'AnatomicImageNumber:13'
'ColorMapMaximum:20'
'ColorMapMinimum:0'
'SpectroscopySliceNumber:3'    

but it is getting written to the textfile like this

AnatomicImage:13,AnatomicImageNumber:13,ColorMapMaximum:20,ColorMapMinimum:0,SpectroscopySliceNumber:3

I have included my code pat of which was borrowed from another post on Stackoverflow.

AnatomicImage = 'AnatomicImage: ';
AnatomicImage = strcat(AnatomicImage, num2str(imNum));
AnatomicImageNumber = 'AnatomicImageNumber: '
AnatomicImageNumber = strcat(AnatomicImageNumber, num2str(imNum));
ColorMapMaximum = 'ColorMapMaximum: ';
ColorMapMaximum = strcat(ColorMapMaximum, num2str(max));
ColorMapMinimum = 'ColorMapMinimum: ';
ColorMapMinimum = strcat(ColorMapMinimum, num2str(min));
SpectroscopySliceNumber = 'SpectroscopySliceNumber: ';
SpectroscopySliceNumber = strcat(SpectroscopySliceNumber, num2str(sliceNum));

fid=fopen('data.txt','wt');

data = {AnatomicImage;AnatomicImageNumber;ColorMapMaximum; ColorMapMinimum; SpectroscopySliceNumber}

txtFun = @(str)sprintf('%s,',str)
xchar = cellfun(txtFun, data, 'UniformOutput', false)
xchar = strcat(xchar{:})
xchar = strcat(xchar(1:end-1),'\n')

fprintf(fid,xchar)

fclose(fid);
Amro
  • 122,595
  • 25
  • 236
  • 442
Ben Fossen
  • 987
  • 6
  • 22
  • 48

1 Answers1

2

Change the relevant section to:

txtFun = @(str)sprintf('%s,\n',str)
xchar = cellfun(txtFun, data, 'UniformOutput', false)


fid=fopen('data.txt','wt');
for i=1:numel(xchar)
    fprintf(fid,'%s',xchar{i})
end
fclose(fid);

Also, consider using safe file-io - see my answer here

Community
  • 1
  • 1
Andrey Rubshtein
  • 20,557
  • 10
  • 65
  • 102