Search code examples
matlabstructmexmatlab-coder

Matlab - making a MEX, Coder cannot classify defined field of a struct array


The MATLAB Coder has proven very helpful to me recently, successfully making a MEX file of a function with parfor in it, wonderfully speeding up a long-running program. However, I just added another line to the code, and Coder is telling me it can't classify a variable in that line:

if any(bullseyes)
    firstHit = bullseyes(1);
    organism(x,y).path(firstHit).hit = targ;
    targsHit = targsHit + 1;
    targsTouched = targsTouched + 1;
end

I hover the mouse over the word hit, at the end of organism(x,y).path(firstHit).hit, and it tells me A variable in a parfor could not be classified. (This is indeed inside a parfor, indeed it's in a for within that parfor, but since there is so much inside the parfor, I decided only to share this much.) It may be helpful to know that bullseyes is redefined every iteration of the for loop containing this if and a little more, y and x are the counter variables for the parfor loop and the for loop containing it, respectively, and targsHit and targsTouched are placeholder variables that transfer their cargo at the end of each x,y combination.

I am surprised that it's not recognizing the class of organism.path.hit for two reasons. In another, nearly identical, block of code that follows this one, the equivalent call organism(x,y).path(firstGlance).hit = targ; gets no objection - though I imagine the interface might be programmed to only object to the first instance of an error when fixing one fixes them all. Also, more significantly, I already told Coder what that field is classified as, on the previous page of the interface. As you can see in the image below, it should recognize this as a double scalar:
Enter Input Types
Any thoughts on why this definition is not going through, and how I might make Coder understand that this scalar field of a struct field of a struct, being defined within a parfor loop, is a scalar?


Solution

  • The error message is "A variable in a parfor could not be classified" is referring to the classification of variables used in parfor loops mentioned on the following documentation page :

    http://www.mathworks.com/help/coder/ug/classification-of-variables-in-parfor-loops.html

    The access

    organism(x,y).path(firstHit).hit

    does not match any of the classifications mentioned on that page. Therefore it is not supported for use within a parfor loop in MATLAB Coder. You could try rewriting the parfor loop in a way that all variable usages match the classifications described in the link. If anything cannot be written to match a classification it can be moved outside the parfor loop.

    Variable usages matching these classifications are needed to ensure that different iterations of the loop can be executed on parallel threads.