MATLAB Answers

0

Check files in current folder (MatLab path)

Lucas 님이 질문을 제출함. 2 Oct 2012
I'm running into a slight problem, I'm trying to generate unique names for some files and I need to check if that name exists in the current folder. Some files are named like:
2Hello
3Hello
Since MatLab can’t have numbers at the beginning of file names, I remove that and get ‘Hello’ and I check if that files exists using something like:
exist(Hello, file);
If that returns zero I make that the file name. So when I do that with the second name, I remove the 3 and I also get ‘Hello’. When I check it with exists it returns 4, so I append a number to the end and get ‘Hello1’ and check that. This works the way that I want it to until I delete the files and try again. The next time I run it on these 2 files I get ‘Hello2’ and ‘Hello3’ back.
I have 2 issues with this. The first is I deleted the files so those names shouldn’t exist anywhere on the MatLab path, and the second is that this folder isn’t even on the MatLab path. I don’t have the current folder that I’m working in on the MatLab ‘SetPath’. If I restart MatLab and I run exists on ‘Hello’ through ‘Hello3’ I get 0’s every time, so does exists check MatLab memory and not the MatLab path like it says, if so I think the file should be updated to say that.
So finally to my question, does MatLab have an alternative to exists? One that just checks the current folder that MatLab is pointing too? I don’t care if it conflicts with another name in a different folder, just as long as it’s unique to that folder. Thanks!

  댓글 수: 0

로그인 to comment.

답변 수: 2

Jan 님의 답변 2 Oct 2012
Jan 님이 편집함. 2 Oct 2012
 채택된 답변

You should use EXIST with an absolute path for files:
currentFolder = cd;
fileExisting = (exist(fullfile(currentFolder, 'File'), 'file') == 2);
Using EXIST without absolute path, Matlab searchs all folders in its PATH.
Now EXIST still considers other object like folders, Java libs and DLLs, e.g. fullfile(currentFolder, 'File.dll'). The comparison with 2 cares for these exceptions also.
I admit, EXIST is too smart for checking for the existence of files. I'm using a faster and more robust Mex file for this job.

  댓글 수: 1

I think exist is often to smart to really be useful.

로그인 to comment.


Daniel Shub 님의 답변 2 Oct 2012

You can use dir. Something like
x = dir;
any(strcmp(fname, {x(~[x.isdir]).name}));

  댓글 수: 1

Yes, it returns . and .., but they are directories (at least in Linux) so left out of the comparison. As for striping the extension you can process each element of {x(~[x.isdir]).name} with fileparts to strip the extension.

로그인 to comment.



Translated by