1

I'm trying to convert a function to C++ in Matlab Coder.. There is a cell variable and while building mex it gives an error.

     R=cell(1,n);
for i=1:wi
        for j=1:hi
            if(cin(i,j)>0)
                     k=cin(i,j);
                    for x=i-2*rx+1:i+2*rx-1
                        for y=j-2*ry+1:j+2*ry-1
                                if(x>=1 && y>=1 && x<=wi && y<=hi)
                                    R{k}=[R{k}, (x-1)*wi+y];
                            end
                        end
                    end
            end
         end
end

It gives error on R{k}=[R{k}, (x-1)*wi+y]; part

'Attempt to access an element that was not defined before use.'

Anybody can help me about this?

1
  • 3
    this is not c++, is your issue related to c++ at all? if not, take the tag out so its not confusing Commented Dec 17, 2020 at 15:19

1 Answer 1

1

For code generation, you have to define (i.e. assign) all cell array elements prior to their use. Here R{k} is used prior to being assigned. Namely, the R{k} on the RHS of that assignment reads that element prior to it having been assigned.

If you intend the elements to be empty matrices, [], then you can declare R like:

% Cells should be varsize to grow them later on
coder.varsize('R{:}');

% Initialize all cells to empty
R = repmat({[]}, 1, n);

for i=1:wi
        for j=1:hi
            if(cin(i,j)>0)
                     k=cin(i,j);
                    for x=i-2*rx+1:i+2*rx-1
                        for y=j-2*ry+1:j+2*ry-1
                                if(x>=1 && y>=1 && x<=wi && y<=hi)
                                    R{k}=[R{k}, (x-1)*wi+y];
                            end
                        end
                    end
            end
         end
end

More details in the MATLAB Coder doc:

https://www.mathworks.com/help/simulink/ug/cell-array-restrictions-for-code-generation.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.