??? Error using ==> fprintf Invalid file identifier. Use fopen to generate a valid file identifier.

Hi, I get this error when running a statistical analysis. Can anyone help me with that? I always used this script and always worked. I have just moved to a group license and everything stopped working. I am using Matlab 2010a (MAC OSX 64-bit). Many thanks. Here is the code:
for cd = 1:NSTIM,
fid = fopen([pwd '/' directory '/Stats_' vec_info(cd).evmarker],'w');
fprintf(fid,'%s\n',[' HbO_2 HHb ']);
fprintf(fid,'%s',['Channel P-val H-val PosMchge Mchange Ntrials']);
fprintf(fid,'%s\n',[' P-val H-val PosMchge Mchange Ntrials']);
for ch = 1:NTRACES,
fprintf(fid,'%6f %6.8f %6f %6.8f %6.8f %6f ',ch, Pval_STIM_oxy(cd,ch),Hval_STIM_oxy(cd,ch),pos_oxy(ch),mean_oxy(ch,cd),Ntrials_oxy(ch,cd));
fprintf(fid,'%6.8f %6f %6.8f %6.8f %6f\n',Pval_STIM_deoxy(cd,ch),Hval_STIM_deoxy(cd,ch),pos_deoxy(ch),mean_deoxy(ch,cd),Ntrials_deoxy(ch,cd));
end
fclose(fid);

Answers (2)

  1. legal file name? what string is produced by "[pwd '/' directory '/Stats_' vec_info(cd).evmarker]"?
  2. add assert( fid >= 3, ... ) to the code
  3. use [ fid, message] = fopen( filename, ...) and output message with the the message of assert

2 Comments

Thanks for your quick answer. Where exactly should I change the code? Where can I use the [fid, message] command? Thanks
You currently have
fid = fopen( [etc]
change that to
[fid, message] = fopen( [etc]

Sign in to comment.

Obviously this line fails:
fid = fopen([pwd '/' directory '/Stats_' vec_info(cd).evmarker],'w');
You could and should catch corresponding problems using:
[fid, msg] = fopen(fullfile(pwd, directory, ['Stats_', vec_info(cd).evmarker], 'w');
if fid == -1
error(msg);
end
I guess, that either the file is existing already and write-protected, or you do not have write permissions to the folder.
FULLFILE considers trailing file separators, e.g. if the current directory is "C:\".

2 Comments

[fid, msg] = fopen(fullfile(pwd, directory, ['Stats_', vec_info(cd).evmarker], 'w'); if fid == -1 error(msg); end
what if i want to change the directory of file, is it possible?
Remove the pwd and set the variable named directory to whatever directory name you want to write to

Sign in to comment.

Asked:

on 3 Oct 2012

Commented:

on 26 Aug 2017

Community Treasure Hunt

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

Start Hunting!