Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Compiled Matlab fgets error

Subject: Compiled Matlab fgets error

From: Ben

Date: 11 Sep, 2012 21:06:08

Message: 1 of 8

I'm experiencing what seems like a common error - I have code which opens files and reads contents, but when I compile said code it throws an InvalidFid error:

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

Error in fgetl (line 34)
..."
and so on.

The problem for me is that my code uses Eeglab to open .gdf files and the fgets error is thrown from inside there. I cannot change that part of the code, so my question is, does the way that I set up the path in the code or compile the program affect its functioning?

FYI, the path is obtained using uigetfile(), and then before the line where the EEG data is read there are several types of text file being read without throwing this error. So that part of the program seems to work ok - it is only when the Eeglab code is called that it fails.
Can anyone shed light on how the compiler affects calls to file read functions?

Subject: Compiled Matlab fgets error

From: dpb

Date: 11 Sep, 2012 21:26:25

Message: 2 of 8

On 9/11/2012 4:06 PM, Ben wrote:
...

> The problem for me is that my code uses Eeglab to open .gdf files and
> the fgets error is thrown from inside there. I cannot change that part
> of the code, so my question is, does the way that I set up the path in
> the code or compile the program affect its functioning?
>
> FYI, the path is obtained using uigetfile(), and then before the line
> where the EEG data is read there are several types of text file being
> read without throwing this error. So that part of the program seems to
> work ok - it is only when the Eeglab code is called that it fails. Can
> anyone shed light on how the compiler affects calls to file read functions?

Well, certainly anything you do re: a path inside code will affect it's
functioning, yes.

One problem often run into when run a compiled app instead of in the
workplace is that the process that is spawned to run the executable may
not have the identical environment (variables, path, home directory,
etc., etc., etc., ....) so files that are visible in the one location
may not be in the other.

Also, w/ another toolbox in play I worry about whether the fid passing
is in a separate context so the 3rd party package isn't seeing the fid
you think it is.

I would think such questions can only be answered w/ specific code
structure to look at--it's too abstract to simply talk about it; one has
to see what actually is being done, specifically to say anything
specific. (Or, I can fall back to the "crystal ball is in the garage
for service again" mantra... :) )

--

Subject: Compiled Matlab fgets error

From: Ben

Date: 12 Sep, 2012 04:56:07

Message: 3 of 8

Hi,

I'll quote the code but there's quite a lot :)

It starts with uigetfile, and runs through some file IO for various types of text files. Some of these functions are Matlab native, some (at least xml2struct) are picked up off F-Ex. They run fine, and for testing they spit out an xls file to show they have worked.
They're acting on a directory location which looks like:
<root folder - obtained by uigetfile>
 - text files
 - <games folder>
 - <game 1>
 - - EEG file
 - <game 2>
 - - EEG file
...

So what I'm wondering now is whether it matters that the root folder is added to the path by addpath(), and the subdirectories are not added explicitly in the same way (they are meant to be added by the same call to addpath).

<code>
    % First file to grab
    fname = 'patient_condition.txt';

    % Find the desired session folder
    if isempty( pathn )
        [fname, pathn] = uigetfile( fname, 'Select Session Data' );
    end
    % Add session folder to path
    addpath( genpath(pathn) );
    % Get list of files in folder
    seshfs = dir( pathn );
    % If there is no 'games' folder, then nothing of interest took place.
    if sum(strcmp({seshfs.name}, 'games'))==0
        disp( ['*#*#*#* There were no games found at ' pathn '; aborting *#*#*#*'] );
        return;
    end

    %% PATIENT CONDITION VALUES
    % Get the patient condition data
    fname = fullfile(pathn, fname);
    fid = fopen(fname);
    pcond = textscan(fid, '%s %f', 'Delimiter', ':');
    % Cut date variable and reduce the score by an order of mag, shorten names
    date = datestr(datenum(num2str(pcond{2}(6)), 'yyyymmddHHMMSS'));
    pcond{1}(6) = []; pcond{2}(6) = [];
    % Get end of session data, append to condition data
    fname = fullfile(pathn, 'session_score.txt');
    fid = fopen(fname);
    if fid ~= -1, ptmp1 = textscan(fid, '%s %f', 'Delimiter', ':');
    else
        disp( '*#*#*#* Session score not found - subbing zeros *#*#*#*' );
        ptmp1 = { {'-'; '-'; 'session_average_score'}, [0.0; 0.0; 0.0] };
    end;
    fname = fullfile(pathn, 'session_summary.txt');
    fid = fopen(fname);
    if fid ~= -1, ptmp2 = textscan(fid, '%s %f', 'Delimiter', ':');
    else
        disp( '*#*#*#* Session summary not found - subbing zeros *#*#*#*' );
        ptmp2 = { {'Effort'; 'Frustration'}, [0.0; 0.0] };
    end
    % Combine the three patient condition files - careful about session score
    % as it reads in 1 line more than there is (due to extra ':' in file)
    if ~isempty( ptmp1 ) && ~isempty( ptmp2 )
        pcond = {[pcond{1}; ptmp2{1}; ptmp1{1}(3)] [pcond{2}; ptmp2{2}; ptmp1{2}(3)]};
    end
    pcond{1}{2} = 'Hrs since sleep';
    pcond{1}{8} = 'Session Score/10';
    pcond{2}(8) = pcond{2}(8)./10;

    % Get IEP stuff: Individual alpha freq
    iep = 0.5;
    fname = fullfile(pathn, '..', 'IEP', 'theta.f');
    tmp = xml2struct( fname );
    iep = [iep str2double( tmp.OpenViBE_dash_SettingsOverride.SettingValue{4}.Text )];
    iep = [iep str2double( tmp.OpenViBE_dash_SettingsOverride.SettingValue{5}.Text )];
    % USE THIS VECTOR TO FIND THE VALUES IN BANDS PER GAME
    iep = [iep iep(3)*2 25 45];

    % For COMPILED CODE, test how far it runs.
    xlswrite( 'testout', pcond{1} );

    %% BASELINE VALUES, SPECTRA & COEFFICIENTS CAN CHANGE EVERY GAME.
    % MAY NEED TO REWRITE THIS SECTION FOR GAME BY GAME PARSING

    blEEG = [];
    blPwr = [];
    blFrq = [];
    blPows = [];
    basedur = '-';
    % Get the beta and theta baseline values, if a baseline was recorded.
    fname = fullfile(pathn, 'baseline.gdf');
    if exist( fname, 'file' ) == 2
        % Use the baseline.gdf to display the baseline spectrum?
       if seshfs( strcmp({seshfs.name}, 'baseline.gdf')==1 ).bytes > 4096
            blEEG = pop_biosig( fname );
            blEEG.data = double(blEEG.data);
            basedur = blEEG.pnts/blEEG.srate;
       end
    end
</code>

dpb <none@non.net> wrote in message <k2oa8k$g25$1@speranza.aioe.org>...
> On 9/11/2012 4:06 PM, Ben wrote:
> ...
>
> > The problem for me is that my code uses Eeglab to open .gdf files and
> > the fgets error is thrown from inside there. I cannot change that part
> > of the code, so my question is, does the way that I set up the path in
> > the code or compile the program affect its functioning?
> >
> > FYI, the path is obtained using uigetfile(), and then before the line
> > where the EEG data is read there are several types of text file being
> > read without throwing this error. So that part of the program seems to
> > work ok - it is only when the Eeglab code is called that it fails. Can
> > anyone shed light on how the compiler affects calls to file read functions?
>
> Well, certainly anything you do re: a path inside code will affect it's
> functioning, yes.
>
> One problem often run into when run a compiled app instead of in the
> workplace is that the process that is spawned to run the executable may
> not have the identical environment (variables, path, home directory,
> etc., etc., etc., ....) so files that are visible in the one location
> may not be in the other.
>
> Also, w/ another toolbox in play I worry about whether the fid passing
> is in a separate context so the 3rd party package isn't seeing the fid
> you think it is.
>
> I would think such questions can only be answered w/ specific code
> structure to look at--it's too abstract to simply talk about it; one has
> to see what actually is being done, specifically to say anything
> specific. (Or, I can fall back to the "crystal ball is in the garage
> for service again" mantra... :) )
>
> --

Subject: Compiled Matlab fgets error

From: Ben

Date: 12 Sep, 2012 06:14:09

Message: 4 of 8

Argh, I just realised my message above was in error - I was talking about subdirectories but in the code I posted it had not even reached the part where it explores subdirectories.

So the code is valid but scratch the bit about directories :)
So then I know the path is good, the file is there, and the code executes file IO on other files from the same dir.
I tried moving the eeglab toolbox to the same folder as the code I am compiling, but didn't help.

Subject: Compiled Matlab fgets error

From: dpb

Date: 12 Sep, 2012 13:08:33

Message: 5 of 8

On 9/12/2012 1:14 AM, Ben wrote:
> Argh, I just realised my message above was in error - I was talking
> about subdirectories but in the code I posted it had not even reached
> the part where it explores subdirectories.
> So the code is valid but scratch the bit about directories :)
> So then I know the path is good, the file is there, and the code
> executes file IO on other files from the same dir. I tried moving the
> eeglab toolbox to the same folder as the code I am compiling, but didn't
> help.

Well, the combination of the two posts has totally confused me -- your
original post says you have an invalid file handle problem w/ a compiled
code.

Now I'm at a loss as to what you meant by 'compiled' here -- you mean
the external package distributed as a (I presume) set of mex functions
or have you tried to compile the overall program and are trying to
execute that?

Clarify the situation, please...

Also, _PLEASE_ do not top-post--conversation follow hard to makes.

--

Subject: Compiled Matlab fgets error

From: Ben

Date: 12 Sep, 2012 14:48:09

Message: 6 of 8

dpb <none@non.net> wrote in message <k2q1f6$60t$1@speranza.aioe.org>...
> On 9/12/2012 1:14 AM, Ben wrote:
> > Argh, I just realised my message above was in error - I was talking
> > about subdirectories but in the code I posted it had not even reached
> > the part where it explores subdirectories.
> > So the code is valid but scratch the bit about directories :)
> > So then I know the path is good, the file is there, and the code
> > executes file IO on other files from the same dir. I tried moving the
> > eeglab toolbox to the same folder as the code I am compiling, but didn't
> > help.
>
> Well, the combination of the two posts has totally confused me -- your
> original post says you have an invalid file handle problem w/ a compiled
> code.
>

Apologies for the confusion. The problem remains the same, much like the song - an invalid file handle with compiled code.
This occurs within the file reader script pop_biosig() from Eeglab, so that I cannot change the code itself.
Hopefully that is clearer?

> Now I'm at a loss as to what you meant by 'compiled' here -- you mean
> the external package distributed as a (I presume) set of mex functions
> or have you tried to compile the overall program and are trying to
> execute that?
>

I have compiled the program and am trying to execute. FYI I'm completely new to compiled Matlab.

> Clarify the situation, please...
>
> Also, _PLEASE_ do not top-post--conversation follow hard to makes.
>
> --

Subject: Compiled Matlab fgets error

From: dpb

Date: 12 Sep, 2012 15:02:00

Message: 7 of 8

On 9/12/2012 9:48 AM, Ben wrote:
...

>
> I have compiled the program and am trying to execute. FYI I'm completely
> new to compiled Matlab.
...

Well, I've never had the compiler so you're ahead of me.

But...

If it runs and finds files successfully in the development environment
but not as a compiled app you're at the point I suggested
originally--the environment of the executable is _NOT_ the same as that
of a session in Matlab.

The discussion of using a path and addpath() etc., certainly looks to me
like that will be the root cause of your problem--the working matlabpath
that Matlab searches is likely not identical in the two environments and
would be a good culprit/place to start.

Add some diagnostic output to display the working environment path in
the code at the various points to see what it actually is at the time of
execution.

Also add error handling on every fopen() call and include the diagnostic
information there...

--

Subject: Compiled Matlab fgets error

From: Ben

Date: 4 Oct, 2012 15:48:09

Message: 8 of 8

Well the solution to that particular problem was to use the mex version of the EEG read function which were available from the Biosig website.

meta = mexSOPEN( fin );
data = mexSLOAD( fin );

where 'fin' is the filename.
The use of the mex functions completely solved the issue of invalid Fid, however to actually use the EEG data which was read, several functions from the Eeglab toolbox are still used - this means they expect the same data format that would be returned by using the pop_biosig() function from Eeglab. The mex functions DO NOT return exactly the same format, thus an explicit conversion is needed, which is given below.
Hope this helps someone, sometime!

<code>
function eeg = mexican( fin )
%%
% PURPOSE: Return the pop_biosig-style data structure of EEG read by mex functions.
% PARAMS: 'fin' - the input file, a gdf
% USAGE:
% Note:
% CALLS: mexSOPEN(), mexSLOAD()

    % Load the file meta-data
    meta = mexSOPEN( fin );
    data = mexSLOAD( fin );
    % Transposed data
    eeg.data = data';
    % Start converting names and matrix orientation etc
    eeg.nbchan = meta.NS;
    eeg.trials = meta.SPR;
    eeg.pnts = meta.NRec;
    eeg.srate = meta.SampleRate;
    for i = 1:meta.NS
        eeg.chanlocs(i).labels = meta.Label(i);
        eeg.chanlocs(i).ref = '';
    end
    eeg.ref = 'common';
    eeg.comment = ['Original file: ' meta.FileName];
    eeg.event = meta.EVENT;
    % These fields have no equivalent from the mex load
    [eeg.filepath, eeg.filename, ~] = fileparts( fin );
    eeg.subject = '';
    eeg.group = '';
    eeg.condition = '';
    eeg.session = [];
    eeg.xmin = [];
    eeg.xmax = [];
    eeg.times = [];
    eeg.epoch = [];
    eeg.etc = [];

</code>

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us