How to continue in a loop when the file does not exist? - matlab

This script download many files. However, I want the loop to continue when it doesn't find any file: File mot found.
for ii=1:length(t2)
d=t2(ii);
if year(d)>=2011
download(d)
end
end
Any ideas? Thanks

I'm guessing download is a function that downloads something from a server, so I don't see how exist will work. Either way, you can simply use a try catch block:
for ii=1:length(t2)
d=t2(ii);
if year(d)>=2011
try
download(d)
catch
end
end
end

You could add an 'if' statement before the download(d) statement to ask whether the file exists. Something like:
for ii=1:length(t2)
d=t2(ii);
if year(d)>=2011
if exist(d) % where d is the file
download(d)
else
continue % Jump to next loop iteration if file doesn't exist
end
end
end
Assuming that 'd' is the file in question that you want to download. You might need to use the file's whole address to make sure Matlab can find it.

In addition to the check before downloading you can do try-catch. This download is likely to throw an error if file is missing or something (load does, but I don't have download). You get this error for load:
Error using load
Unable to read file 'lala.m'. No such file or directory.
Now the same with try-catch:
try
load('lala.m')
catch
disp('No such file')
end
It will display No such file, which might not be the real error thrown by load, but you can do multiple catches.
This doesn't have a large advantage when the only thing that can go wrong is "file does not exist", but if you have multiple possible fail points you can have single try-catch (if you don't care what went wrong, just that something did) instead of a long cascade of ifs checking everything.

Related

Matlab: track all file handles that were opened/touched by script

I want to find all dependencies of my script (and/or all subfunctions/subscripts), but not only functions that are called but also external files that are loaded or touched (fopen). matlab.codetools.requiredFilesAndProducts (documentation here) doesn't capture the touched filenames, my next idea, shadow the fopen function using something like below (to copy the filename to a log file), resulted in an unexpected recursive loop.
failed because of (unexpected) recursive loop, where somehow the 'builtin' fopen is not called, rather this function itself:
function varargout=fopen(varargin)
%write opened filename to log file somewhere
varargout=builtin('fopen',varargin{:}); %attempt to call built-in fopen() as usual
end
I also checked Mathworks depencey reports etc, to no use. Any ideas? Thank you.

How to ignore error/exception during process of a list?

Learning kdb+q. Without loss of generality, let's say if I have a list of file paths and wants to open each one of them, but I want to make sure Q opens whatever it exists. Say if one of the file paths doesn't exist, then continue to process others.
I know protected evaluation can let me handle error #[open_many_files_func; files; errhandler].
But how to make it not fail in the middle and continue with the rest?
You can use 'each' to iterate over the files
#[open_many_files_func; ; errhandler] each files
If it's just existance of the file that you're checking for (and not that the function fails due to a problem with the file), then you could also use the key function to check the existance of the file.
q)system "ls"
"file1"
"file2"
"file4"
q)b: a where count each a: key each `:file1`:file2`:file3`:file4
`:file1`:file2`:file4
Once you have the list of files, you can just do
open_many_files_func each b
https://code.kx.com/q/ref/key/

Warning: Unable to load Toolbox Path Cache in a for loop

I have a code that is like this
echo "try;
start=tic;
sv=fopen('$SIZE_VECTOR_1','r');
vector=fscanf(sv, '%d');
fclose(sv);
tama=fopen('$TAMANO_EVAL','r');
taman=fscanf(tama, '%d');
fclose(tama);
fid=fopen('$LISTA_WORDS_EVAL','r');
lista=fscanf(fid,'%f',[taman,vector]);
fclose(fid);
v_writehtk('${OUT_DIR_FEA_EVAL}/${name}.fea',lista,0.01,6);
toc(start)
catch
disp('THROWN MATLAB ERROR:');
e=lasterror;
disp(e);
e.message
e.stack.file
e.stack.name
e.stack.line
end
" > ${OUT_DIR_VEC_EVAL}/${M_FILE}.m;
I have to do this matlab code multiple times in a loop with different values, It is a "for loop" that takes different files with different names, so the for loop is in my shell script code and at each loop this matlab code is created in a txt file and then executed by matlab, I am not doing it in parallel. v_writehtk is a matlab code that transform the files taked by the loop and transforms it to another format.
sometimes in the loop I receive the Warning: Unable to load Toolbox Path Cache , so I want to know whether or not this affect to my results and how can I solve this?, I tried things like "exit" at the end of the code or "rehash toolboxcache" at the beginning and end of the code but I keep receiving this warning sometimes. Please someone help me on this.

Matlab: error using fprintf

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
Try using fclose all before calling this script again. Often when testing, the file handle is never released (an error occurs before the file is closed), causing fopen on the same file to fail.
The better way to do this would be to use a more fail-safe construct:
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
I am running Win 10 and matlab 2015a, but it happens in mine too.
finally, I realise that the matlab.exe can't write file in the folder /../bin/
so, change to
Nameout=['C:\Users\yourname\DesktopNash'];
try it, then tell me what' going on.
Okay, so as I said, I don't know Matlab... I hadn't properly specified the path for writing! So it was reading the input but I guess didn't know where to write to. Thanks for the answers, it did help me narrow down the problem!

Can't close text file because MATLAB uses it after failed execution

I call a function (containing fopen and fclose) from the Command Window and then after MATLAB encounters an error that I fix (the runtime of the program stops after I save my corrections), I want to delete the file it created, in order to repeat the process. However, MATLAB, somehow, still has the file open and typing in fclose(f), in the Command Window does not make MATLAB let go of the file.
function something(something)
f = fopen('something.txt', 'w');
%statments with fprintf
fclose(f);
end
You may not have access to the handle f from outside the function, in which case you can try fclose('all') from the Matlab command window.
Generally it is best practice to use a try .. catch ... statement around code that uses a file, so that you always call fclose and release the handle if an error occurs.
If you are still unable to delete the file, and assuming it is not locked by another process (for example if you are viewing it externally in Windows Notepad), it may be that you are calling library functions from Matlab and that the shared library maintains the file lock. In this case, try reloading the library using the unloadlibrary and loadlibrary commands.
Using an onCleanup object can be very useful in this case.
Here's your code rewritten to use onCleanup - the fclose will now get called when the function terminates whether normally, or because of an error.
function something(something)
f = fopen('something.txt', 'w');
closer = onCleanup( #()fclose(f) );
% statements with fprintf
end
The documentation also includes an example for exactly this case.