Error in calling a function and writing to file

1 回表示 (過去 30 日間)
Mitul Dattani
Mitul Dattani 2017 年 12 月 23 日
コメント済み: Walter Roberson 2017 年 12 月 24 日
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);

採用された回答

Walter Roberson
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 件のコメント
Mitul Dattani
Mitul Dattani 2017 年 12 月 24 日
Yeah it works when i run matlab as admin, how would I go about changing the directory for matlab though so I dont have to run it as admin again? I always assumed when running adding the directory to the path did it for me but obviously thats not the case.
Walter Roberson
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 ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by