简体   繁体   中英

How do I initialize a multidimensional object array using size() in MATLAB correctly?

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. eg

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. eg

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?

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));

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