My mex function ignores my if statement - matlab

I have a mex function that takes in a field of a struct in the third input (i.e. prhs[2]), which is a boolean. If true, it will parse information from the fourth input (i.e. prhs[3]). In a nutshell, this is the code excerpt:
mxValue = mxGetField(prhs[3], 0, "change"); mxLogical *change;
change = mxGetLogicals(mxValue);
mexPrintf("true/false: %i \n", *change);
mexEvalString("drawnow;");
if ( change ) {
mexPrintf("...Parsing info... \n");
mexEvalString("drawnow;");
mxValue = mxGetField(prhs[3], 0, "info");
nRows = mxGetM(mxValue); nCols = mxGetN(mxValue);
Eigen::Map<Eigen::VectorXd> info((double *)mxGetPr(mxValue),nRows);
}
As you can see, I do a printout to see whether the input prhs[2] is true or false. Even if the function prints out false, the if statement gets executed regardless, because I can see the printout ...Parsing info....
Why is my MATLAB mex function ignoring my if statement?

C is not MATLAB! C is C!
You are checking if pointer change has a value. It does indeed have a value, a memory direction e.g. #72BA21, to the location where the value of the boolean is stored.
You can either check the contents of whats inside that specific direction if(*change) as #buzjwa suggest, or grab the information on the array, instead of a pointer to it, using mxGetData.
As a side note: learn to debug, or at least, print statements. a simple mexPrintf() call would have shown you what change contains

Related

MATLAB's mxGetFieldByNumber and mxGetFieldNameByNumber return incongruent results

I have a C mex routine that is iterating over subfields of a structure. Sometimes calling mxGetFieldByNumber() returns NULL when mxGetFieldNameByNumber() returns a string for the same field idx. Here is a toy:
numFields = getNumberOfFields( currentField );
for( fieldIdx = 0; fieldIdx < numFields; fieldIdx ++){
subField = mxGetFieldByNumber( currentField, 0 , fieldIdx );
fieldName = mxGetFieldNameByNumber(currentField, fieldIdx );
}
I have read through the documentation of both functions. A NULL can be returned if (in this example) currentField were not a mxArray which I know is not the case because mxGetFieldNameByNumber() returns something sensible. Insufficient heap space could be the problem but I've checked that and it is on 400kb. NULL can also be returned when no value is assigned to the specified field but I've looked and it appears the value is zero.
Any thoughts?
When a struct is created at the MATLAB level or in a mex routine via mxCreateStruct, not all field elements are necessarily populated. In such case, MATLAB physically stores a NULL pointer (i.e., 0) in those data spots (a struct is essentially an array of mxArray pointers). E.g., take the following code snippet assuming X doesn't exist yet:
X.a = 5;
X(2).b = 7;
The X struct variable actually has four elements, namely X(1).a, X(1).b, X(2).a, and X(2).b. But you only set two of these elements. What does MATLAB do with the other elements? Answer: It simply stores NULL pointers for those spots. If you subsequently access those NULL spots in your MATLAB code, MATLAB will simply create an empty double matrix on the fly.
At the mex level, a similar thing happens. When you first create the struct with mxCreateStruct, MATLAB simply fills all of the element spots with NULL values. Then you can populate them in your code if you want, but note that leaving them as NULL is perfectly acceptable for returning back to MATLAB. The routine mxGetFieldByNumber actually gets the element mxArray pointer, and mxGetFieldNameByNumber gets the name of the field itself ... two very different things. If you get a NULL result from a valid mxGetFieldByNumber call (i.e. your index is not out of range), that simply means this element was never set to anything. You should never get a NULL result from a valid mxGetFieldNameByNumber call, since all field names are required to exist.
If you were to pass in the X created above to a mex routine and then examine prhs[0] you would find the following:
mxGetFieldByNumber(prhs[0],0,0)
returns a pointer to an mxArray that is the scalar double 5
mxGetFieldByNumber(prhs[0],0,1)
returns a NULL pointer
mxGetFieldByNumber(prhs[0],1,0)
returns a NULL pointer
mxGetFieldByNumber(prhs[0],1,1)
returns a pointer to an mxArray that is the scalar double 7
mxGetFieldNameByNumber(prhs[0],0)
returns a pointer to the string "a"
mxGetFieldNameByNumber(prhs[0],1)
returns a pointer to the string "b"

Issues writing my first function in MATLAB

I'm new to programming and writing my first function for MATLAB. The name of the function should be "picalc".
The purpose is to accept an "x" and "y" value as input arguments. These values must be plugged into x^2+y^2, and if this result is less than or equal to 1, return true. Otherwise, return false.
Here is what I have so far:
function[true,false]=picalc(x,y);
if x^2+y^2<=1
return true
else
return false
end
Can anyone tell me why this won't work? As it stands, I get the following error:
Error: File: picalc.m Line: 6 Column: 13
Unexpected MATLAB expression.
Thank you very much for your expertise!
In MATLAB, return does not return value as an output of a function call but rather returns control to the invoking function (see documentation here). As such, it does not take argument, because what it does is merely redirecting the flow of the program to the function/statement that invokes the function/statement containing the return statement.
Your function should be written like this:
function result = picalc(x,y);
if x^2+y^2<=1
result = true;
else
result = false;
end
The variable on left hand side of the function declaration is the output variable. By assigning value to this valuable, you are "returning" an output.

Understanding the syntax

I have this couple of lines which is difficult to understand..
oframes1 = do_localmax( difofg.octave{o}, 0.8*thresh, difofg.smin ) ;
oframes = [oframes1 , do_localmax( - difofg.octave{o}, 0.8*thresh, difofg.smin)] ;
here,
do_localmax is a function
thresh is a variable
difofg is also a function
I understand that the 1st line calls the function and passes the parameters but it is difficult understanding the second line and also what kind of syntax is difofg.octave{o}
Syntactically:
difofg is not a function; it's a variable, probably a struct or a class object. difofg.octave and difofg.smin get the element named octave or smin from that struct/object.
difofg.octave is apparently a cell array, and difofg.octave{o} gets the oth element of that cell array.
The second line creates an array with two elements: the first is oframes1, and the second is the result of the second call to do_localmax. Maybe this equivalent code will make it clearer what's happening:
oframes1 = do_localmax( difofg.octave{o}, 0.8*thresh, difofg.smin);
oframes2 = do_localmax( -difofg.octave{o}, 0.8*thresh, difofg.smin);
oframes = [oframes1, oframes2];

matlab - what is the equivalent of null / None / nil / NULL etc.?

In most OO languages, where variables may point to objects, they may also have a null value, which is highly convenient.
In Matlab, I have a function which parses a command, and then returns a cell array, or false (which is equal to zero — which is another common pattern) if it fails:
function re = parse(s)
...
if (invalid)
re = false;
return;
end
end
The problem is that when I check the result, it gives an error:
re = parse(s);
if (false == re)
Undefined function 'eq' for input arguments of type 'cell'.
I've written a function to check it without an error: strcmp('logical', class(re)) && false == re, but that seems to be really slow for use in hot areas of the code, and also inconvenient if I have to add this function to every M file I'm writing.
Using NaN is even worse, because besides throwing that error, it also isn't equal to itself.
What's a better alternative for use with this pattern?
You can use the isequal function to compare any two items without causing that error. For example:
if isequal (re, false)
%code here
end
A good alternative is to use the empty array: [] and isempty(re) to check. This doesn't throw the error.
Reference: http://www.mathworks.com.au/matlabcentral/newsreader/view_thread/148764
If you can change the function parse one solution would be to return two output arguments [re status] = parse(s), where status would be logical variable. Set it to true in case of success, and to false otherwise.
I would use the empty cell array {} if it is not a valid result otherwise. Using empty matrices is MATLAB standard (see Evgeni Sergeev's answer), but using an empty cell array instead of an empty numeric array ensures that you'll always end up with the same type of result.
If, on the other hand, the empty cell array {} is a valid result of your function, then I'd use an exception to signalize a problem:
if invalid
error('Parse:InvalidArgumentError', 'The input is invalid.');
end
Make sure to use an appropriate error ID (first argument to error) so that you can catch exactly that exception when you call the function:
try:
result = parse(something);
catch ME
if strcmp(ME.identifier, 'Parse:InvalidArgumentError')
fprintf('Ooops\n');
else
% Some other error
ME.rethrow();
end
end
I think the problem is that matlab functions don't return pointers but copies of values.
IMHO the best best approach would be to define your own "pointer" class. Inside you can define an "isNull()" command or even override comparison to produce the behavior you desire.

What is the neatest way of passing flags to a Matlab function?

I'm designing a function that takes as argument one structure and any number of flags. The function will contain a couple of ifs checking whether a specific flag is set.
What is the neatest way to achieve this? I was thinking about passing the flags as separate string arguments. Is there a neater solution?
I would do it like using varargin and ismember:
function foo(arg1,arg2,varargin)
flag1=ismember('flag1',varargin);
flag2=ismember('flag2',varargin);
flag3=ismember('flag3',varargin);
And you can call the function like that:
foo(a1,a2,'flag3','flag1')
This will activate flag1 and flag3.
Pass in a struct of flags:
options = struct(...
'Flag1', true, ...
'Flag2', true, ...
'MySpecifFlag', false ...
);
Foo(st, options);
To get a list of all the flags that were explicitly set by the user, use fieldnames:
passedOptions = fieldnames(options);
This returns a cell array whose elements are strings - these strings are the flags set by the user; the ith element of the array is the ith flag set by the user.
Access the value of each flag that was set:
options.(passedOptions{i}) %# gets the value of the flag corresponding to passedOptions{i}
Probably you can pass varargin -
The even will be names of the flags and the odd their values (except the first)
function Foo(st, varargin)
end
Then pass values like this:
Foo(st, 'Flag1', true, 'Flag2', false)
Foo(st, 'Flag3', true, 'MyFlag2', false,'MySpecialFlag',false)
Foo(st)
To access the variable arguments use
varargin{2}, varargin{3},
etc..
To check whether a specific flag was passed, do
flagNames = varargin{2:end};
ismember('MyFlag',flagNames )
You can pass the flags as a string with 0s and 1s. The order can be fixed or you can also pass a cell array of flag names.
flagstr = '101'; %# string passed as argument
flaglog = flagstr=='1'; %# logical vector, can be accessed as flaglog(i)
fname = {'flag1','flag2','flag3'}; %# flag names, can be passed as argument or defined in the function
fvalue = num2cell(flaglog); %# create cell array
flags = cell2struct(fvalue, fname, 2); %# create a structure, so you can access a flag with flags.flag1
You need to take care to match the length of fvalue and fnames. if they are different you can either generate an error or somehow correct it (remove the extra flags or fill the absent by default value).
varargin is the way to go for parsing a variable number of arbitrary input arguments. If you want somemore control over the calling syntax of the function (i.e. optional/required arguments) then I suggest looking into Matlab's input parser.