Why does fclose generates an ans return in the workspace?

5 Ansichten (letzte 30 Tage)
Mats
Mats am 13 Sep. 2012
Why does fclose() returns 'ans' in the workspace? If I change the line in status = flose(fid); the ans disappears and 'status' obviously appears. Why is flose() not suppressed?
directory = 'D:\Documents\MATLAB\Data\';
files = dir([directory,'*.nta']);
for iFile = 1:numel(files)
fid = fopen([directory,files(iFile).name]);
temp = textscan(fid,'%f %s %s %f %f %f %f %f', 'Delimiter', '\t', 'HeaderLines', 28);
fclose(fid);
end

Antworten (2)

Jan
Jan am 13 Sep. 2012
Bearbeitet: Jan am 13 Sep. 2012
The output of fclose() is not suppressed, because there is no reason to suppress it. ans contains the uncaught output of the last processed command. Even from a MEX-function the first output can be replied even for nlhs==0 and the output appears in ans. The trailing semicolon suppresses the output to the command window.
Perhaps your problem gets clear, when you explain, what you want to achieve.
BTW, although I do not know a reason why fclose should fail, it is a good programming practice to catch the output in general to check for errors. I use this in larger functions:
fid = fclose(fid);
Then fid is set to 0 or -1 and a further usage is blocked. Example:
fid1 = fopen(File1);
fid2 = fopen(File2);
...
fid1 = fclose(File1);
fwrite(fid1, rand(10)); % Typo! It should be "fid2"! But error is caught.
Well, although this helps to write cleaner code, it is still not clean: The replied flag is a flag, which is only accidently an invalid file-ID. Better:
status = fclose(File1);
if status == -1, error...
A drawback of fid=fclose(fid) is that MLint warns about an unused variable, if fid is not used afterwards.

Titus Edelhofer
Titus Edelhofer am 13 Sep. 2012
Hi,
that's because fclose returns a status. From the doc:
status = fclose(...) returns a status of 0 when the close operation is successful. Otherwise, it returns -1
And therefore there is nothing special about fclose: if you are not interested in the output of a function, use the ; ...
Titus
  1 Kommentar
Titus Edelhofer
Titus Edelhofer am 13 Sep. 2012
Sorry, read your post again: if you write
fclose(fid);
you should see no output either. But yes, you will generate an ans variable anyway.
Titus

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by