num2cell at high dimensions - is this a bug?

1 view (last 30 days)
royk
royk on 21 Nov 2019
Edited: Kavya Vuriti on 16 Jan 2020
Matlab help of num2cell(A,[DIM1, DIM2, ...]) says
"All DIMn inputs must be an integer with a value from NDIMS(A) to 1."
The function though does accept DIMs larger than NDIMS(A), yet gives strange looking output. Here is an example:
>> cell2mat(num2cell([1 2],[2 4]))
ans =
1 2
>> cell2mat(num2cell([1 2],[4 2]))
ans(:,:,1,1) =
1
ans(:,:,1,2) =
2
Is this sensible at all? Or, is this a bug?

Answers (1)

Kavya Vuriti
Kavya Vuriti on 16 Jan 2020
Edited: Kavya Vuriti on 16 Jan 2020
Hi,
The function ‘num2cell’ is intended to work properly when all the values of dim vector are between 1 and ndims(A), if A is input array. When a value greater than ndims(A) is given, it works the following way:
The input array (say A) is of size 5 x 6 for example, which can be interpreted as 5 x 6 x 1. When dim is in order, each cell in the output cell array has a numeric array with the same size as A, except with size 1 in the dimensions NOT specified by dim. num2cell with different values of dim argument gives the following results:
c = num2cell(A,1): each cell in c is 5x1(x1)
c = num2cell(A,2): each cell in c is 1x6(x1)
c = num2cell(A,3): each cell in c is 1x1(x1)
c = num2cell(A,[1 2]): each cell in c is 5x6(x1)
c = num2cell(A,[1 3]): each cell in c is 5x1(x1)
c = num2cell(A,[2 3]): each cell in c is 1x6(x1)
This behavior of num2cell, when the values in dim vector are greater than ndims(A) is due to “size function returns value 1 when queried dimension is greater than ndims(A).
When dim is not in order, the result will be: take the result for num2cell(A,sort(dim)), and then permute each cell's dimensions to get the right order of the dimensions specified by dim. So, the output looks the following way:
c = num2cell(A,[2 1]): each cell in c is 6x5(x1)
c = num2cell(A,[3 1]): each cell in c is 1x1x5
c = num2cell(A,[3 2]): each cell in c is 1x1x6
The number of cells can however be computed as numel(A)/prod([size(A,dim(1)),...,size(A,dim(N))]), where N is the length of dim vector.

Categories

Find more on Numeric Types in Help Center and File Exchange

Tags

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!