简体   繁体   中英

Converting Matlab code to C++ with Matlab Coder - Cell problem

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?

For code generation, you have to define (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM