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!