Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab 'exist' returns 0 for a file that definitely exists!

I'm running Matlab 7.8.0 under Windows.

I am calling an external utility using dos() which creates a file in the current directory. I the file is created correctly, but it cannot be seen by exist or fopen, which return 0 and -1 respectively. The filename is correct!

>> pwd
ans = 
I:\

>> ls

file1.asc     file2.asc     file3.asc

>> exist('file1.asc')           % this file was there before
ans =
     2

>> exist('file2.asc')           % this file is newly created
ans =
     0

to confirm it's not an odd/problematic filename, I checked from a Cygwin shell:

/cygdrive/i/ $ if [ -f file2.asc ]; then echo "OK"; fi
OK

So the file is good. I tried renaming it

/cygdrive/i/ $ mv file2.asc test

and in Matlab

>> ls

file1.asc      file3.asc      test

>> exist('test')
ans =
     0

If I exit and restart Matlab it works fine. But I need to dynamically create the file and then access it!

like image 793
Sanjay Manohar Avatar asked Dec 05 '22 01:12

Sanjay Manohar


2 Answers

Very mysterious.

You could try:

  • The rehash command to see if that helps.
  • The two-argument version of exists: exist('foo.txt', 'file')
like image 95
nsanders Avatar answered Dec 16 '22 12:12

nsanders


The Matlab exist() command is not a simple filesystem operation; it also looks at variables, functions, etc. Since you're on I:, I'm assuming that's a network drive, and you're probably running in to the dir contents caching problem that Jonas mentions.

Here are a couple other workarounds, in case nsanders' two-arg exist() or Jonas' change notification fixes don't work for you.

Try using absolute paths to the files, like "fopen('I:\file2.asc')", instead of relative paths and pwd. Matlab will treat unqualified filenames as "partial paths" for both exist() and fopen(), and that interacts with the directory info caching. Ls() does not work with partial paths, which may be why it can see the file and the other functions can't.

You can use Java from within Matlab to do a simpler file existence test.

java.io.File('file2.asc').exists()

Or since the ls() command is showing the file you want, you can just implement the file existence check on top of ls.

ismember({'file2.asc'}, ls())

The "{ }" is necessary to make ismember() operate at the string level instead of the char level.

If you're still having trouble reading it, try doing a lower level read with Java from within Matlab. That will tell you whether it's specifically Matlab's I/O functions that are having trouble, or of the process itself lacks access to the file. Try this. If you get a char out of it, that means your Matlab.exe process can see the file.

istr = java.io.FileInputStream('file2.asc')
c = char(istr.read())
like image 40
Andrew Janke Avatar answered Dec 16 '22 12:12

Andrew Janke