Reputation: 2183
I am trying to write a text file using fprintf on matlab. I use a for loop:
fID = fopen('fileName','w');
fSpec = cat(2,repmat('%s', 1, 3),'\n');
for k=1:10
to_write = [num2str(k) ',' num2str(k*k)];
fprintf(fID, fSpec, to_write);
end
fclose(fID);
A file is written, but on one line only. I tried opening it with gedit and matlab.
What is wrong?
Upvotes: 3
Views: 5939
Reputation: 9696
Your format specifier is somewhat weird.
to_write
will be a plain string, so why do you construct fSpec to be %s%s%s\n
?
If you want one line per loop, you can simply do:
for k=1:10
to_write = [num2str(k) ',' num2str(k*k)];
fprintf(fID, '%s\n', to_write);
end
EDIT:
In case %s%s%s\n
was designed to match the three strings in [num2str(k) ',' num2str(k*k)]
: This is not necessary.
The result of [num2str(k) ',' num2str(k*k)]
will simply be a single string - so you only need one '%s'
format specifier, instead of three.
Upvotes: 4
Reputation: 683
I was able to find two little things in your code.
First, you want to hit return after writing each line, thus \n
. Second, you were trying to write a string value using fprint
since you were using %s
, changing it to %d
solved it I think!
So the updated code should read:
fID = fopen('fileName','w');
fSpec = cat(2,repmat('%d', 1, 3),'\n');
for k=1:10
to_write = [num2str(k) ',' num2str(k*k)];
fprintf(fID, fSpec, to_write);
end
fclose(fID);
Upvotes: 0