主要内容

Resolve Error: Cannot Reference Handle Object Outside of Loop

Issue

If you create or allocate a handle object inside a for-loop, you cannot use the handle object outside of the loop when:

  • You assign the handle object to an array element or structure field.

  • You do not fully reallocate the handle object in each iteration of the for-loop

If the code generator determines that either of these conditions are true, code generation fails with this error:

Cannot allocate this handle object. For code generation, a handle object allocated inside a loop cannot be referenced outside of the loop.

Possible Solutions

To determine when to destroy a handle object that is created or allocated in a for-loop, the code generator checks whether the MATLAB® code allows multiple copies of the handle object to persist outside of the loop. If the code generator determines that the MATLAB code allows multiple copies of the handle object to persist outside of the for-loop, code generation fails.

For example, consider the function usehandle_error, which uses the handle class MyClass.

classdef MyClass < handle
    properties
        prop
    end
    methods
        function obj = MyClass(x)
            obj.prop = x;
        end
    end
end

function out = usehandle_error(n)
c = cell(1,n);
for i = 1:n
    c{i} = MyClass(i);
end
out = c{n}.prop;
end

Code generation for usehandle_error fails because the function assigns the handle object MyClass to the cell array element c{i} inside the for-loop. Therefore, the code generator determines that multiple copies of the handle can persist outside of the loop.

To resolve this error, try one of these solutions.

Allocate Handle Object Outside for-Loop

Preallocate the handle object before the for-loop, and do not assign the handle object to a cell array element inside the for-loop. For example:

function out = usehandle1(n)
c = repmat({MyClass(0)},1,n);
for i = 1:n
    c{i}.prop = i;
end
out = c{n}.prop;
end

Fully Assign Handle Object in Each Loop Iteration

Assign the handle object to the cell array itself, not to an element of the cell array. For example:

function out = usehandle2(n)
c = MyClass(0);
for i = 1:n
    c = MyClass(i);
end
out = c.prop;
end

Specify Constant Number of Loop Iterations

If you know the number of loop iterations, you can specify this number in the MATLAB function or at code generation time. For example:

function out = usehandle3
n = 10;
c = cell(1,n);
for i = 1:n
    c{i} = MyClass(i);
end
out = c{n}.prop;
end
Alternatively, specify a constant input value when you generate code by using coder.Constant. For example, use this command to generate code for function usehandle_error:
codegen usehandle_error -args {coder.Constant(10)}
Code generation successful.

See Also

| |

Topics