Error in calling a function and writing to file
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2017-12-23
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 个评论
Walter Roberson
2017-12-24
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!