4

This is a script written by someone else, and I don't understand why it is giving me this error (I don't really know Matlab, but this appears to be a fairly straightforward script, so I'm a bit stumped). The file starts with

    clear all
    filein=['Runs/'];
    Namein1=['AIC'];
    Nameout=['Nash'];

It then does a bunch of calculations to get Nash-Sutcliffe coefficients (not important for this issue) and then tries to write the results to one file:

    %Write Nash
       %Output file writing
    %Write file header
    D={'Conbination','Nash with Error','Nash-error','RMSE','RMSE-error',...
    'AIC', 'MinNash', 'MaxNash'};
    NameOut=[filein,Nameout, '.txt'];
    fileID = fopen(NameOut,'w');
    for i=1:length(D)-1
        fprintf(fileID,'%s\t',D{i});

Then more stuff follows, but this is where I get the error message:

    Error using fprintf
    Invalid file identifier.  Use fopen to generate a valid file identifier.

    Error in Nash_0EV_onlyT (line 169)
    fprintf(fileID,'%s\t',D{i});

I don't get what is wrong here? The script specifies the file, and uses fopen...? Isn't it supposed to create the file Nash.txt with the fopen statement (this file currently does not exist in my folder Runs/)? What am I missing? Thanks!

PS I am running Matlab2013a (group license via the university) on a MacBook Pro with OSX 10.8

4

3 回答 3

3

fclose all在再次调用此脚本之前尝试使用。通常在测试时,文件句柄永远不会被释放(在文件关闭之前发生错误),导致fopen同一个文件失败。

更好的方法是使用更安全的构造:

NameOut = [filein Nameout '.txt'];

fileID = fopen(NameOut,'w');

if fileID > 0
    try
        for i = 1:length(D)-1
            fprintf(fileID,'%s\t',D{i});
        end  
        fclose(fileId);  

    catch ME        
        fclose(fileId);
        throw(ME);

    end       

else
    error('Error opening file.');

end
于 2013-10-02T14:47:41.520 回答
1

我正在运行 Win 10 和 matlab 2015a,但它也发生在我的身上。

最后,我意识到 matlab.exe 无法在文件夹 /../bin/ 中写入文件

所以,改为

Nameout=['C:\Users\yourname\DesktopNash'];

试试看,然后告诉我发生了什么。

于 2015-10-26T08:43:15.423 回答
0

好的,正如我所说,我不知道 Matlab ......我没有正确指定写作路径!所以它正在读取输入,但我想不知道在哪里写。感谢您的回答,它确实帮助我缩小了问题范围!

于 2013-10-02T15:57:40.250 回答