MATLAB: How to compile MATLAB files that call Neural Network Toolbox functions into stand-alone applications, in MATLAB releases R13 or older

ccodecompilerDeep Learning Toolboxexportgenerationjavaneuralnnnnetr13standalone

I would like to generate a stand-alone application from MATLAB code that uses the Neural Network Toolbox. Is it possible with MATLAB Compiler 3.0 (R13)?

Best Answer

Compiler releases before 3.0 (R13) do not support deployment of MATLAB objects within functions; the Neural Network Toolbox therefore does not allow you to export a trained network to C, C++, or Java for these releases.
If you are trying to use a trained network in a C or Java environment you can use the following steps:
1) Train the network 'completely' in the Neural Network Toolbox.
2) Use the GENSIM function to create a Simulink block of the trained network.
3) Use the Real Time Workshop to create a standalone application.
Alternately, you can save the weight matrix and bias matrix along with other information about the network into a data file and read it into your C, C++, or Java application.
Here is an example that demonstrates this:
 
P = [0 1 2 3 4 5 6 7 8 9 10];
T = [0 1 2 3 4 3 2 1 2 3 4];
% Before training, use the following code
net = newff([0 10],[5 1],{'tansig' 'purelin'});
Y = sim(net,P);
plot(P,T,P,Y,'o')
Now, train the system using the following code:
 
net.trainParam.epochs = 50;
net = train(net,P,T);
Y = sim(net,P);
plot(P,T,P,Y,'o')
%%Using GENSIM
gensim(net)
Then the input and output are replaced by the From File and To File block. The From File reads from the newfrom.mat file that is created using the following:
 
t=[0:10];
u=ones(1,11);
tu=[t;u];
save newfrom.mat tu;
Suppose we want to tune only the following weight:
 
my_neuralnet/Neural Network/Layer 1/IW{1,1}/IW{1,1}(1,:)'
So we go to this Constant block and change the value to a symbolic value, say "Pooh". Then we need to inline parameters and configure Pooh as a tunable parameter. Then we need to build the model. To change Pooh to 100, you can simply use the following:
 
pooh = 100;
myrtp = rsimgetrtp('my_neuralnet');
save myparamfile myrtp;
!my_neuralnet -p myparamfile.mat