필터 지우기
필터 지우기

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 CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by