MCC compiler "Internal Error: Could not determine class of method" - matlab

I have Matlab script that I am trying to compile as an executable that will run on a headless server as part of a large batch process. The script calls functions and classes written by several non-programmers (scientists) over the span of more than a decade, and I am having a difficult time getting it to compile.
The script will run in a Matlab instance, but MCC gives me an error that I do not quite understand:
Compiler version: 5.1 (R2014a)
Dependency analysis by REQUIREMENTS.
Error using matlab.depfun.internal.MatlabSymbol/proxy (line 405)
Internal1 Error: Could not determine class of method
"/home/me/MyCode/#tsd/Data.m". Number of classes checked:
17.
#tsd/tsd.m looks like this:
function tsa = tsd(t, Data)
% tsd Creates tsd object (tsd = class of timestamped arrays of data)
%
% tsa = tsd(t, Data)
%
% INPUTS:
% t - list of timestamps - must be sequential, but don't have to be continuous
% Data - data, possibly an array. If data is n-dimensional, then time should be the FIRST axis.
% OUTPUTS:
% tsa - a tsd object
%
% Completely compatible with ctsd.
%
% Methods
% tsd/Range - Timestamps used
% tsd/Data - Returns the data component
% tsd/DT - Returns the DT value (mean diff(timestamps))
% tsd/StartTime - First timestamp
% tsd/EndTime - Last timestamp
% tsd/Restrict - Keep data within a certain range
% tsd/CheckTS - Makes sure that a set of tsd & ctsd objects have identical start and end times
% tsd/cat - Concatenate ctsd and tsd objects
% tsd/Mask - Make all non-mask values NaN
%
% ADR 1998, version L4.0, last modified '98 by ADR
% RELEASED as part of MClust 2.0
% See standard disclaimer in ../Contents.m
if nargin == 0
tsa.t = NaN;
tsa.data = NaN;
tsa = class(tsa, 'tsd');
return
end
if nargin < 2
error('tsd constructor must be called with T, Data');
end
tsa.t = t;
tsa.data = Data;
tsa = class(tsa, 'tsd');
and the Data.m file:
function v = Data(tsa, ix)
% tsd/Data Retrieves data from tsd
%
% d = Data(tsa)
% d = Data(tsa, ix)
%
% INPUTS:
% tsa - tsd object
% ix - alignment list (timestamps)
% OUTPUTS:
% v - the tsa.Data
%
% if called with alignment list, returns those tsa.Data(ix)
% if called without, returns complete tsa.Data
%
% ADR 1998, version L4.1, last modified '98 by ADR
% RELEASED as part of MClust 2.0
% See standard disclaimer in ../Contents.m
switch nargin
case 2
f = findAlignment(tsa, ix);
v = SelectAlongFirstDimension(tsa.data,f);
case 1
v = tsa.data;
otherwise
error('Unknown number of input arguments');
end
So the script calling the tsd function runs just find in the Matlab session, but the compiler throws the error described above. This is my first time working with Matlab and I am totally stumped. There is another class with a method named "Data", but that shouldn't cause this problem, could it?

I was having the exact same problem and was able to come up with a workaround.
I was facing this problem when I was compiling the MATLAB library using the command
mcc -W cpplib:LibName -T link:lib main.m -a './' -d 'dll_destintaion_dir'
LibName: DLL name
main.m: MATLAB entry point
dll_destintaion_dir: destination where DLL created will be stored
The error was gone when I compiled using this command instead
mcc -W cpplib:LibName -T link:lib main.m -a 'full_path_of_project_folder/*'
-d 'dll_destintaion_dir'
Note: This method does not add folders recursively to the archive. So subfolders have to be added explicitly using another -a flag in the command shown above.

Related

Passing parameters to a Matlab function

I have a very simple question, but I didn't figure out how to solve this.I have the function definition below:
function model = oasis(data, class_labels, parms)
% model = oasis(data, class_labels, parms)
%
% Code version 1.3 May 2011 Fixed random seed setting
% Code version 1.2 May 2011 added call to oasis_m.m
% Code version 1.1 May 2011 handle gaps in class_labels
%
% Input:
% -- data - Nxd sparse matrix (each instance being a ROW)
% -- class_labels - label of each data point (Nx1 integer vector)
% -- parms (do sym, do_psd, aggress etc.)
%
% Output:
% -- model.W - dxd matrix
% -- model.loss_steps - a binary vector: was there an update at
% each iterations
% -- modeo.parms, the actual parameters used in the run (inc. defaults)
%
% Parameters:
% -- aggress: The cutoff point on the size of the correction
% (default 0.1)
% -- rseed: The random seed for data point selection
% (default 1)
% -- do_sym: Whether to symmetrize the matrix every k steps
% (default 0)
% -- do_psd: Whether to PSD the matrix every k steps, including
% symmetrizing them (defalut 0)
% -- do_save: Whether to save the intermediate matrices. Note that
% saving is before symmetrizing and/or PSD in case they exist
% (default 0)
% -- save_path: In case do_save==1 a filename is needed, the
% format is save_path/part_k.mat
% -- num_steps - Number of total steps the algorithm will
% run (default 1M steps)
% -- save_every: Number of steps between each save point
% (default num_steps/10)
% -- sym_every: An integer multiple of "save_every",
% indicates the frequency of symmetrizing in case do_sym=1. The
% end step will also be symmetrized. (default 1)
% -- psd_every: An integer multiple of "save_every",
% indicates the frequency of projecting on PSD cone in case
% do_psd=1. The end step will also be PSD. (default 1)
% -- use_matlab: Use oasis_m.m instead of oasis_c.c
% This is provided in the case of compilation problems.
%
I want to use this function, but I don't figure how to set the parameters, or use the default values. What is the variable parms in this case, it is an object that keep all the other variables? Can I make something python like syntax where we put the name of the parameter plus value? For example:
model = oasis(data_example, labels_example, agress = 0.2)
Additionally, If I have understood correctly, I get two Objects in the Output, which is model and modeo, so I need to make this call to receive all contents this function returns?
[model,modeo] = oasis(data_example, labels_example, ?(parms)?)
From your function definition it seems like params is simply a placeholder for the parameters. Typically the parameters themselves are passed as pairs of inputs in the form:
model = oasis(data, class_labels, 'do_sym',do_symValue, 'do_psd', do_psdValue,...)
where do_symValue and do_psdValue are the values you want to pass as the respective parameters.
As for the functions return value, it returns a single struct with members W, loss_steps, and parms. I believe that what you thought as a second output (modelo) is simply a typo in the text - at least based on the function's definition.
From the documentation above, I don't know which one is the right, but there are two common ways for optional parameters in matlab.
parameter value pairs:
model = oasis(data, class_labels, 'do_sym',1,'do_psd',0)
structs:
params.do_sym=1
params.do_psd=0
model = oasis(data, class_labels, params)
Probably one of these two possibilities is right.

How to access variables in the properties block of a Matlab System Object?

I am working on a simple System Object in Matlab/Simulink.
It looks like this :
classdef realtime_header_detectorSO < matlab.System & matlab.system.mixin.Propagates
% correlateHeader
%
% This template includes the minimum set of functions required
% to define a System object with discrete state.
properties
Header
%nrOfBitsInPreviousStep=0;
s=100;
d=zeros(1,s);
end
properties (DiscreteState)
end
properties (Access = private)
max_nr_of_packets=20;
max_packet_length_in_bytes=300;
current_packet=1;
% Pre-computed constants.
% h = commsrc.pn('GenPoly', [9 5 0],'NumBitsOut', 8,'InitialStates',ones(1,9));
% data=logical(zeros(max_nr_of_packets,max_packet_length_in_bytes*8));
end
methods (Access = protected)
function setupImpl(obj,u)
% Implement tasks that need to be performed only once,
% such as pre-computed constants.
end
function [maxCorr]= stepImpl(obj,u)
eml.extrinsic('num2str');
coder.extrinsic('sprintf');
% Implement algorithm. Calculate y as a function of
% input u and discrete states.
%y = size(u,1);
symbols=sign(u);
c=abs(conv(flipud(obj.Header),[symbols; symbols]));
maxCorr=max(c);
% maxCorr
if(maxCorr==36)
idx36=find(c(1:size(symbols,1))==36);
disp('header(s) detected at the following location(s) in bytes:');
disp(sprintf('%15.4f \n',idx36/8));
nrOfSymbols=size(symbols,1);
disp(['out of nr. of total symbols: ' num2str(nrOfSymbols)]);
disp('------');
% maxCorr
end
% y=obj.pBufferIdx;
end
function resetImpl(obj)
% Initialize discrete-state properties.
end
function varargout = isOutputFixedSizeImpl(~)
varargout = {true};
end
function varargout = getOutputSizeImpl(obj)
varargout = {[1 1]};
end
end
end
However when I compile/run it I get the following error:
The System object name 'realtime_header_detectorSO' specified in MATLAB System block 'freqScanningRT/Sync and
Find Header/detect header' is invalid.
Caused by:
Undefined function or variable 's'.
However (!) the following code compiles and runs just fine :
classdef realtime_header_detectorSO < matlab.System & matlab.system.mixin.Propagates
% correlateHeader
%
% This template includes the minimum set of functions required
% to define a System object with discrete state.
properties
Header
%nrOfBitsInPreviousStep=0;
s=100;
% d=zeros(1,s);
end
properties (DiscreteState)
end
properties (Access = private)
max_nr_of_packets=20;
max_packet_length_in_bytes=300;
current_packet=1;
% Pre-computed constants.
% h = commsrc.pn('GenPoly', [9 5 0],'NumBitsOut', 8,'InitialStates',ones(1,9));
% data=logical(zeros(max_nr_of_packets,max_packet_length_in_bytes*8));
end
methods (Access = protected)
function setupImpl(obj,u)
% Implement tasks that need to be performed only once,
% such as pre-computed constants.
end
function [maxCorr]= stepImpl(obj,u)
eml.extrinsic('num2str');
coder.extrinsic('sprintf');
% Implement algorithm. Calculate y as a function of
% input u and discrete states.
%y = size(u,1);
disp(obj.s);
symbols=sign(u);
c=abs(conv(flipud(obj.Header),[symbols; symbols]));
maxCorr=max(c);
% maxCorr
if(maxCorr==36)
idx36=find(c(1:size(symbols,1))==36);
disp('header(s) detected at the following location(s) in bytes:');
disp(sprintf('%15.4f \n',idx36/8));
nrOfSymbols=size(symbols,1);
disp(['out of nr. of total symbols: ' num2str(nrOfSymbols)]);
disp('------');
% maxCorr
end
% y=obj.pBufferIdx;
end
function resetImpl(obj)
% Initialize discrete-state properties.
end
function varargout = isOutputFixedSizeImpl(~)
varargout = {true};
end
function varargout = getOutputSizeImpl(obj)
varargout = {[1 1]};
end
end
end
So I can access s in the stepImpl(obj,u) as obj.s but I cannot access s inside the properties block, where it is defined !
Now this is confusing.
Is there way to access s inside the properties block ?
The problem is that I have to use the properties block because if I try this :
function setupImpl(obj,u)
% Implement tasks that need to be performed only once,
% such as pre-computed constants.
d=zeros(1,obj.s);
end
then I get :
Error due to multiple causes.
Caused by:
Problem creating simulation target MEX-file for model 'freqScanningRT'.
Simulink detected an error
'Computed maximum size is not bounded.
Static memory allocation requires all sizes to be bounded.
The computed size is [1 x :?].'.
The error occurred for MATLAB System block 'freqScanningRT/Sync and Find Header/detect header'. See line
34, column 15 in file
'path/realtime_header_detectorSO.m'.
The error was detected during code generation phase.
Start code generation report.
To prevent this error, use one of the following:
* Modify the System object to avoid code that does not support code generation.
* Change 'Simulate using' parameter to 'Interpreted Execution'.
Any idea how to refer to variables in the properties blocks ?
There must be a way to do this.
You should be able to use
properties
s = 100;
d = zeros(1,100);
end
right? If you already have the 100 as a default for s, you should also be able to provide this as part of the default for d.
I'm guessing that you're trying to avoid doing that because you feel uncomfortable repeating the "100". But I'd also guess that really, "100" is some sort of magic number that your system depends on; so really, you should try to pull it out as a constant in any case, whether it's repeated or not.
So in that case, you might improve things with
properties (Constant)
MYCONSTANT = 100;
end
properties
% Reference Constant class properties with the class name
s = realtime_header_detectorSO.MYCONSTANT;
d = zeros(1, realtime_header_detectorSO.MYCONSTANT);
end
You're not going to be able to do what you're originally trying to do - it's not possible to reference the name of one property within the property definition block when defining another property (even though you can perfectly well reference it within a method). I guess I understand why you find that confusing - but to clear up your confusion, note that you have no guarantee over the order in which MATLAB instantiates default values for properties. If it tried to create d before it had created s, it would obviously fail.
You can avoid this problem all together by initializing the properties in the constructor.

Expected scalar value: MATLAB Coder

I get the following error while using MATLAB coder for generating a c++ code from m file with a call to a c function ompmex.c
C function calls always return scalar values but a non-scalar value is expected here.
My code is:
function [D,gamma] = DSGD2(X,H) %#codegen
[Xr,Xc]=size(X);
[Hr,Hc]=size(H);
D=zeros(Hr,Hc,'double');
D=X(:,11:210);
d1=sqrt(sum(D.*D)); D=D./repmat(d1,Xr,1);
beta=zeros(Xr,Xc,'double');
beta=coder.ceval('ompmex',H,X,H'*H,200);
Can anybody help on this. I am not getting a working answer online
function [D,gamma] = DSGD2(X,H) %#codegen
[Xr,Xc] = size(X);
[Hr,Hc] = size(H);
D = zeros(Hr,Hc,'double');
D = X(:,11:210);
d1 = sqrt(sum(D.*D));
D = D./repmat(d1,Xr,1);
% coder.ceval is tricky. I recommand to use it only if the function is
% created by c-coder too (and not as mex function!)! you need a c executable
% or a c library (generated before you trigger codegen for DSGD2).
% further more, ceval can not handle multiple
% outputs. as a workaround, always use structs for output - and for
% input too!
s = struct('beta',(zeros(Xr,Xc,'double')));
% make it work in matlab too and call ompmex function
if coder.target('MATLAB')
s = ompmex(H,X,H'*H,200);
else
coder.ceval('ompmex_initialize')
s = coder.ceval('ompmex',H,X,H'*H,200);
coder.ceval('ompmex_terminate')
end
% read out stuct value
beta = zeros(Xr,Xc,'double');
beta = s.beta;
gamma = 0; % not given by you, but c-coder needs it. so change to what ever you need
end

matlab - is there a function which echo text of file ?

Since it is not possible to have a script and a function definition in the same file , I thought to echo the function which I want to attach in the script such that I get a script with function code and then some usage with this function .
For example -
func1.m
function [result] = func1(x)
result=sqrt(x) ;
end
script1.m
echo(func1.m) ;
display(func1(9))
Desire output for script1.m
function [result] = func1(x)
result=sqrt(x) ;
end
display(func1(9))
3
Have you any idea for that ?
Since a convoluted solution was already proposed, why not stating the obvious?
Matlab has a built-in command that does exactly what you want. It is called type:
>> type('mean')
will give you this:
function y = mean(x,dim)
%MEAN Average or mean value.
% For vectors, MEAN(X) is the mean value of the elements in X. For
% matrices, MEAN(X) is a row vector containing the mean value of
% each column. For N-D arrays, MEAN(X) is the mean value of the
% elements along the first non-singleton dimension of X.
%
% MEAN(X,DIM) takes the mean along the dimension DIM of X.
%
% Example: If X = [0 1 2
% 3 4 5]
%
% then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1
% 4]
%
% Class support for input X:
% float: double, single
%
% See also MEDIAN, STD, MIN, MAX, VAR, COV, MODE.
% Copyright 1984-2005 The MathWorks, Inc.
% $Revision: 5.17.4.3 $ $Date: 2005/05/31 16:30:46 $
if nargin==1,
% Determine which dimension SUM will use
dim = min(find(size(x)~=1));
if isempty(dim), dim = 1; end
y = sum(x)/size(x,dim);
else
y = sum(x,dim)/size(x,dim);
end
You could use this:
function echo(mfile)
filename=which(mfile);
if isempty(filename)
fprintf('Invalid input - check you are inputting a string.');
return;
end
fid=fopen(filename,'r');
if (fid<0)
fprintf('Couldn''t open file.');
end
file=fread(fid,Inf);
fclose(fid);
fprintf('%s',file);
end
This will open a file, read it, and print it. Note that you need to provide the input as a string, i.e. with single quotes around it, and need to have '.m' at the end:
echo('fread.m')
Not
echo(fread.m) % This won't work
echo('fread') % This won't work
Just for completeness, there's also dbtype which prepends line numbers.

Matlab: renaming workspace elements from command window?

The GUI of Matlab allows me to rename any element in the workspace by right-clicking on the element and selecting the 'rename' option. Is it possible to do this from the command window as well?
These are things you can easily test for yourself, and you should do so. That is the best way to learn, to discover.
Regardless, the answer is no, you cannot change a variable name in that way from the command window. The command window is mainly for keyboard input only.
Edit: The question was apparently about doing that change by a command in the command window, not to be done via a mouse. (Why not tell us that up front?)
There is no explicit command that does such a rename. However, nothing stops you from writing it yourself. For example...
function renamevar(oldname,newname)
% renames a variable in the base workspace
% usage: renamevar oldname newname
% usage: renamevar('oldname','newname')
%
% renamevar is written to be used as a command, renaming a single
% variable to have a designated new name
%
% arguments: (input)
% oldname - character string - must be the name of an existing
% variable in the base matlab workspace.
%
% newname - character string - the new name of that variable
%
% Example:
% % change the name of a variable named "foo", into a new variable
% % with name "bahr". The original variable named "foo" will no
% % longer be in the matlab workspace.
%
% foo = 1:5;
% renamevar foo bahr
% test for errors
if nargin ~= 2
error('RENAMEVAR:nargin','Exactly two arguments are required')
elseif ~ischar(oldname) || ~ischar(newname)
error('RENAMEVAR:characterinput','Character input required - renamevar is a command')
end
teststr = ['exist(''',oldname,''',''var'')'];
result = evalin('base',teststr);
if result ~= 1
error('RENAMEVAR:doesnotexist', ...
['A variable named ''',oldname,''' does not exist in the base workspace'])
end
% create the new variable
str = [newname,' = ',oldname,';'];
try
evalin('base',str)
catch
error('RENAMEVAR:renamefailed','The rename failed')
end
% clear the original variable
str = ['clear ',oldname];
evalin('base',str)
You can rename variables in the command window as follows:
%# create a variable
a = 3;
%# rename a to b
b = a;clear('a');
EDIT
If you want to rename your variable to another variable stored in a string, you can use ASSIGNIN
a = 3;
newVarName = 'b';
assignin('base',newVarName,a);
clear('a') %# in case you want to get rid of the variable a