# Assign a Sub Array to Array Knowing the Number of Dimensions at Run Time

2 views (last 30 days)
Royi Avital on 10 Feb 2022
Commented: Royi Avital on 11 Feb 2022
Assume we have tA and tB with the same number of dimesions. We also have all(size(tB) <= size(tA)) == true.
The task is to embed tB in tA. Something like: tA(1:size(tB, 1), 1:size(tB, 2), ..., 1:size(tB, n)) = tB. Yet since we know the number of dimensions only at runtime, it can't be written explicitly like that.
The question, is there an efficient way to do so without eval or explicitly computer the cartesian product and use sub2ind()?

Royi Avital on 10 Feb 2022
Edited: Royi Avital on 11 Feb 2022
OK, It turns out it can be done using Cell Arrays:
vSizeB = size(tB);
numDims = length(vSizeB); %<! Equals to ndims(tB)
cIdx = cell(numDims, 1);
for ii = 1:numDims
cIdx{ii} = 1:vSizeB(ii);
end
tA(cIDx{:}) = tB;
Royi Avital on 11 Feb 2022
@Stephen, Well you edited the comment. It was, at first, only num2cell().

Rik on 10 Feb 2022
There is probably a better way, but you can fill a cell array with the index vectors (simple loop with ndims), and then use this:
tA(inds{:}) = tB;