2

I am trying to initialize an object array.

From the MATLAB documentation 1 and 2, I know that you assign the last array element to an object of the and the rest of the array should be filled with default constructed objects. e.g.

object_array(2,2) = object; % create 2 x 2 of class 'object'

I have done this in several places in my code and it has worked fine.

But I've found that for one of my classes it doesn't work.

I have an object array of objA of size 1x2x2, and I want to create an object array of objB of that size. Now objB has a constructor, and so I've made sure the constructor handles the case that the constructor has no arguments, so that the object array of objB can be default filled. e.g.

function objb = objB(parameter)
if (nargin > 0)
% do stuff with parameter
end
end

Now here's the funny part: I try to construct the objB object array using the size of objA array.

# breakpoint 1
objBArray(size(objAArray)) = objB;
# breakpoint 2

When I reach breakpoint 1,

size(objAArray) = 1, 2, 2

But when I reach breakpoint 2,

size(objAArray) = 1, 2, 2

and

size(objBArray) = 1, 2

How come objBArray isn't the same size as objAArray?

Is the problem having a constructor?

1 Answer 1

1

size(objAArray) is a vector which MATLAB will treat as indices for assignment. Since size(objAArray) is [1 2 2], objBArray(size(objArray)) = objB will simply place a reference to objB in elements 1, 2, and 2 of the existing objBArray array. Since objBArray does not exist yet, MATLAB will yield a 1 x 2 array of objects just as it would for normal numbers

a([1 2 2]) = 3;
%   3   3

size(a)
%   1   2

What you actually want instead is

a(1,2,2) = 3;   % Instead of a([1 2 2]) = 3

To accomplish this, you need to convert size(objAArray) to a cell array using num2cell and use {:} indexing to yield a comma separated list to use as the subscripts since you want each entry of the vector as a separate subscript for assignment

inds = num2cell(size(objAArray));
objBArray(inds{:}) = objB;

Alternately, you could use repmat to initialize objBArray with the objects obtained using the default constructor.

objBArray = repmat(objB(), size(objAArray));
Sign up to request clarification or add additional context in comments.

3 Comments

If I was to use the repmat using a handle class objB, would every object in the array point to the same data or would they be independent objects?
@SamJones They would all be the same default object, unfortunately.
And as I understand it using the inds subscript method would refer to different data objects as I understand from this documentation.

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.