简体   繁体   中英

MATLAB .NET assembly (Undefined function or variable 'feedforwardnet')

I'm trying to integrate MATLAB 2010b with Visual Studio 2008 Professional.

I have the following MATLAB method.

function varargout = perform( func, varargin )

%% // Set default values
workspaceDirectory = ['Results/MatlabWorkspace_' datestr(now, 'yyyy-mm-dd_HH-MM-SS')];

clear args
args = struct('workspacePath', [ workspaceDirectory '/workspace.mat'], ...
              'testArray', [], ...
              'k', 50, ...
              'rate', 0.0001, ...
              'trainingDataPath', 'P2AT_LaserImageVectorList.csv', ...
              'network', 'feedforwardnet', ...
              'initialWeights', [], ...
              'divideFcn', 'dividerand', ...
              'trainRatio', 70/100, ...
              'testRatio', 15/100, ...
              'valRatio', 15/100, ...
              'trainInd', [], ...
              'testInd', [], ...
              'valInd', [], ...
              'trainFcn', 'trainlm', ...
              'performFcn', 'mse', ...
              'biasConnect', [0; 0; 0], ...
              'layerSize', [9; 4; 1], ...
              'layerTransferFcn', ['tansig '; 'tansig '; 'purelin'], ...
              'max_fail', 10, ...
              'mu_dec', 0.04, ...
              'useInitialWeights', false, ...
              'saveResults', true);

% // Returns a modified properties structure
args = getopt(args,varargin);

args.layerTransferFcn = cellstr(args.layerTransferFcn);

if args.saveResults && ~strcmpi(func,'test')
    if (exist(workspaceDirectory, 'dir') ~= 7)
        mkdir(workspaceDirectory);
    end
end

if (strcmpi(func,'test'))
    try
        load(args.workspacePath, '-regexp', '.*');
    catch err
        Warning(err.message);
        varargin{1,1} = null;
        return;
    end

    data_inputAngle = args.testArray(2501);
    data_inputPCA = args.testArray(1:2500);

    if size(data_inputPCA,1) == 1
        data_inputPCA = data_inputPCA';
    end

    switch(featureExtractionMethod)
        case {'gha','apex'}
            % // [W, errvals] = gha(data_inputPCA, k, varargin{1,3});
            data_PCs  = W' * data_inputPCA;
            data_inputNN = [data_PCs; data_inputAngle];

        case 'nnmf'
            % // [W,H,D] = nnmf(data_inputPCA',k);
            data_PCs  = H * data_inputPCA;
            data_inputNN = [data_PCs; data_inputAngle];

        case 'pcaProcess'

        otherwise
            warning = 'ERROR: no feature extraction method has been defined.';
            Warning('ERROR: no feature extraction method has been defined.');
            varargout{1,1} = null;
            return;
    end

    % // Just to test to see if it recognizes 'feedforwardnet'.
    testnet = feedforwardnet;    % // <------------------------------- LINE 81

    % // Saving all the workspace variables to see if they are all correctly processed.
    save('all');

    varargout{1,1} = net(data_inputNN); %// <------------------------- LINE 86

    end
end

And this is how I create my DLL file to import in Visual Studio:

%%// Determine path names
workdir = pwd();
outdir = fullfile(workdir, 'Output');
dnetdir = fullfile(workdir, 'dotnet');

%%// Determine file names
mfile = fullfile(workdir, 'perform.m');
dnetdll = fullfile(dnetdir, 'dotnet.dll');

%%// Build .NET Assembly
eval(['mcc -N -d ''' dnetdir ''' -W ''dotnet:dotnet,' ...
        'dotnetclass,0.0,private'' -T link:lib ''' mfile '''']);

So everything works perfectly fine when I use MATLAB Engine's COM interface to run the routine inside MATLAB from C#:

/*
 * This function calls the routine inside
 * MATLAB using the MATLAB Engine's COM interface
 */
static private float MatlabTestDebug(float[] testData, Double targetAngle)
    {
        Array X = new double[testData.Length + 1];
        testData.CopyTo(X, 0);
        X.SetValue((double)targetAngle, testData.Length);

        Array zerosX = new double[X.GetLength(0)];

        MLApp.MLAppClass matlab = new MLApp.MLAppClass();

        matlab.PutFullMatrix("testArray", "base", X, zerosX);
        matlab.PutWorkspaceData("workspacePath", "base", "workspace.mat");

        // Using Engine Interface, execute the ML command
        // contained in quotes.
        matlab.Execute("cd 'c:\\Users\\H\\Documents\\Project\\Source Code\\MatlabFiles';");
        matlab.Execute("open perform.m");
        matlab.Execute("dbstop in perform.m");
        matlab.Execute("result = perform('test', 'workspacePath', 'workspace.mat', 'testArray', testArray);");
        matlab.Execute("com.mathworks.mlservices.MLEditorServices.closeAll");

        return (double)matlab.GetVariable("result", "base");
    }

But when I use the .NET assembly, it's not recognizing 'feedforwardnet'. I used to get an error on line 86 ( net(data_inputNN) ). So I added a line to test to see if it at least recognizes 'feedforwardnet', but it didn't.

Note: I'm loading some variables from a file including "net" which is a neural network ( load(args.workspacePath, '-regexp', '.*'); )

Also in the MATLAB method if I load a saved "network" from file and then save it to see how it processes the network, it will save it as a "struct" instead of a "network".

I'm assuming it's loading it as a struct to begin with.

I also had this problem inside MATLAB 2009b itself. That's the reason I'm using MATLAB 2010b now, because apparently MATLAB 2009b didn't have this particular neural networks toolbox.

Following is the C# code to use the .NET assembly.

/*
 * Calls the method from inside a .NET assembly created with MATLAB
 * using Builder for .NET.
 */
private float MatlabTest(float[] testData, Double targetAngle)
    {
        if (testData != null)
        {
            dotnetclass AClass = new dotnetclass();

            Array X = new double[testData.Length + 1];
            testData.CopyTo(X, 0);
            X.SetValue((double)targetAngle, testData.Length);

            MWNumericArray XNumericArray = new MWNumericArray(X);

            MWArray[] RetVal = AClass.perform(1, "test",
                "workspacePath", "workspace.mat",
                "testArray", XNumericArray);

            Array result = ((MWNumericArray)RetVal[0]).ToVector(MWArrayComponent.Real);

            return (float)result.GetValue(0);
        }
        else
        {
            return 0f;
        }
    }

I'm getting this error in Visual Studio:

... MWMCR::EvaluateFunction error ...
Undefined function or variable 'feedforwardnet'.
Error in => perform.m at line 81.

NOTE: version of my compiler and softwares:

Compiler: Microsoft Visual C++ 2008 SP1 in C:\\Program Files (x86)\\Microsoft Visual Studio 9.0

MATLAB: R2010b (64-bit)

Visual Studio: MVS 2008 professional (.NET Framework 3.5 SP1)

Microsoft Windows SDK 6.1


Recent Updates:

I've added the path of the neural network toolbox in mcc .

eval(['mcc -N -p ''C:\Program Files\MATLAB\R2010b\toolbox\nnet'' -d ''' dnetdir ''' -W ''dotnet:dotnet,' ...
    'dotnetclass,0.0,private'' -T link:lib -v ''' mfile '''']);

Now I get these messages in mccExcludeFiles.log :

C:\\Program Files\\MATLAB\\R2010b\\toolbox\\nnet\\nnet\\@network\\network.m

called by C:\\Program Files\\MATLAB\\R2010b\\toolbox\\nnet\\nnet\\nnnetwork\\cascadeforwardnet.m (because of toolbox compilability rules)

C:\\Program Files\\MATLAB\\R2010b\\toolbox\\nnet\\nnet\\@network\\network.m

called by C:\\Program Files\\MATLAB\\R2010b\\toolbox\\nnet\\nnet\\nnnetwork\\feedforwardnet.m (because of toolbox compilability rules)

The only answer I could come up with (which not a solution to the problem) was from Creating standalone application that contains neural network toolbox functions , stating that:

You will not be able to compile any function which trains the network (like ADAPT). Though the link does not explicitly list these funcions (like ADAPT), they fall under the 'All other command line functionality'.

However, you can deploy a M function code which uses a pre-trained network. I believe the SIM function will deploy fine.

The workflow I see is:

  1. In MATLAB, train you network using test input/output
  2. Save the network (MAT file?)
  3. Create a deployable function which then uses the pretrained network for new data. The network itself would not change/adapt/train in this function
  4. Compile and deploy the above function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM