Hi!
I'm trying to write data to a csv-file based on some image processing done by my matlab-script. The data is stored in a cell where the number of rows equals the number of images with each column consisting of some numerical value describing some feauture in the images. I use the fprintf function for this, and it worked great when I had a fixed amount of columns... Let's say I had 3 features, i.e. three columns with numbers. Then I would just write something like:
for row=1:Nrows
fprint(fid,'%s,%f,%f,%f\n',results{row,:})
end
(The first entry is just the file name of each image.) Now however I want to describe a variable number of features, let's say N features. Then I modify the formatspec string to:
formatspec = ['%s' repmat(',%f',1,N) '\n']
This puts in all the entries alright, but completely ignores newline characters... Do you have any idea why, and maybe how to fix it -- preferrably by just correcting the formatspec string somehow? I am using Matlab2016a by the way.
Thanks in advance!
P.S.: Here is a minimal example that you can play around with.
results = {'1.tif',1,2; '2.tif',3,4};
fid = fopen('myfile.csv','w');
for row=1:length(results(:,1))
fprintf(fid, ['%s' repmat(',%f',1,length(results(1,:))) '\n'], results{row,:});
end
fclose(fid);

 Akzeptierte Antwort

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam am 3 Okt. 2016

0 Stimmen

The right code is
results = {'1.tif',1,2; '2.tif',3,4};
fid = fopen('myfile2.csv','w');
repmat(',%f',1,length(results(1,:)))
for row=1:length(results(:,1))
fprintf(fid, ['%s' [repmat(',%f',1,length(results(1,:))-1) '\n']], results{row,:});
end
fclose(fid);

2 Kommentare

Søren Hanghøj Møller
Søren Hanghøj Møller am 3 Okt. 2016
Bearbeitet: Søren Hanghøj Møller am 3 Okt. 2016
Thanks! :-)
Just out of curiosity: Do you know why your solution works, i.e. what does the extra brackets do?
Edit: I see know that I put one '%f' too many... very embarrassing! Thanks again Asad for helping me with this problem.
you can uses [ and ] for making bigger vectors or even bigger strings.It is used here for joining string together.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB finden Sie in Hilfe-Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by