Error in calling a function and writing to file
1 view (last 30 days)
Show older comments
Mitul Dattani
on 23 Dec 2017
Commented: Walter Roberson
on 24 Dec 2017
I'm trying to call a function out of a script, it's a simple one as we've just started, but I keep getting an error on my fprintf line. Theoretically its supposed to work through different files where one is the function and one is the script whilst both are in the same directory.
This is the function:
function [out]=summation(N)
S=0;
for k=1:N
S=S+(1/k^2);
end
out=S;
end
This is the script
fid = fopen('summationfile.txt', 'w');
for i=1:50
sumvalue=summation(i);
fprintf(fid,'N= %.0f \t S= %.4f \r\n',i,sumvalue);
end
fclose(fid)
Initially I was getting an error about just one line but figured its because the files are separate and if I can get them to work locally moving them to different files wont be as difficult so at the moment they are in the same file and this is the error I receive.
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in summationfile (line 5)
fprintf(fid,'N= %.0f \t S= %.4f \r\n',i,sumvalue);
0 Comments
Accepted Answer
Walter Roberson
on 23 Dec 2017
Change
fid = fopen('summationfile.txt', 'w');
to
filename = 'summationfile.txt';
[fid, msg] = fopen(filename, 'w');
if fid < 0
error('Failed to open file "%s" because "%s"', filename, msg);
end
4 Comments
Walter Roberson
on 24 Dec 2017
When you are writing files, MATLAB always assumes that you want to write into your current directory unless you give the path to where you want to write. So the easiest is to use cd to change directories to a directory that you do your MATLAB work in.
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!