error when using fprintf

can anyone tell me where I'm going wrong here.
clear all
data = rand(365,1);
filename = fullfile('file','test.txt');
fid = fopen(filename,'w');
fprintf(fid,'%s\n',data);
fclose(fid)
I'm trying to save a column vector into a .txt file but get the error:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
The error says that I need to use fopen but I have used it so I'm not sure why an error occurs!

Réponses (2)

Walter Roberson
Walter Roberson le 20 Fév 2012

1 vote

Your fopen() is failing, but you are not checking for that.
Your code is attempting to create a file named "test.txt" in a directory named "file" relative to the current directory. Is that your intention? Does the directory exist?

3 commentaires

Richard
Richard le 20 Fév 2012
yes that was my intention. The name of the directory wasn't actually called file neither is 'data' the actual data that i'm using, just an example.
When taking what was mentioned by image analyst into consideration and my poor example I now have:
clear all
data = rand(1,365);
filename = fullfile('C:\Users\Woolway\Documents\MATLAB','test.txt');
fid = fopen(filename,'w');
fprintf(fid,'%f\n',data);
fclose(fid)
This produces a .txt file but not as a column vector as shown in matlab, shouldn't \n account for this?
Walter Roberson
Walter Roberson le 20 Fév 2012
You may need to open with 'wt' rather than with 'w' . 'wt' is for text files, and 'w' is for binary files.
Richard
Richard le 20 Fév 2012
that works, thank you very much.

Connectez-vous pour commenter.

Image Analyst
Image Analyst le 20 Fév 2012

1 vote

Try adding this line right before the fullfile() line
if ~exist('file', 'dir')
% The (badly named) folder called "file" does not exist.
% Create that folder.
mkdir('file');
end
Beyond that, you're opening a file not in text mode and then using a text format specifier (%s) to write out numerical data. What do you think that will do? Maybe you should use %f instead.

Catégories

En savoir plus sur File Operations dans Centre d'aide et File Exchange

Question posée :

le 20 Fév 2012

Community Treasure Hunt

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

Start Hunting!

Translated by