I would like to extract a sub cell-array from a cell array, but for some reason, the indexing rules for cell arrays don't work as they do for regular arrays.
For example,
T = cell(4,4);
for i = 1:4
for j = 1:4
T{i,j} = [(j-1)*4 + i];
end
end
which produces
T =
4×4 cell array
[1] [5] [ 9] [13]
[2] [6] [10] [14]
[3] [7] [11] [15]
[4] [8] [12] [16]
But when I extract a 2x2 subarray from the upper left corner, I get
{T{1:2,1:2}}
ans =
1×4 cell array
[1] [2] [5] [6]
Why don't I get a 2x2 cell array?
I can reshape the array to get
reshape({T{1:2,1:2}},2,2)
ans =
2×2 cell array
[1] [5]
[2] [6]
but it isn't obvious why I should need to do this. Unless I am missing something, I don't see any ambiguity in applying indexing rules to cell-arrays in the same way they are used for regular arrays.
Ultimately, I would like to be able to rearrange blocks to create a new cell array, i.e.
S = {T{[1 3 4],[1 3 4]}}
Is there a better way to do this other than using reshape?
Note : It was pointed out this question is a duplicate of this question. I didn't see those original posts. And perhaps, had I only had one dimensional cell arrays, I would have never come across the problem I had above. For example, if I had had
P = {[1],[2],[3],[4]}
then
{P{1:2}}
and
P(1:2)
both produce
1×2 cell array
[1] [2]
Using my T
from above, though, the following are different :
{T{1:2,1:2}}
ans =
1×4 cell array
[1] [2] [5] [6]
T(1:2,1:2)
ans =
2×2 cell array
[1] [5]
[2] [6]
I may be dragging out this point, but I do think it is very odd that Matlab unravels 2d cell arrays when using {}
, but not when using ()
. I know that {}
can sometimes mean a "list" rather than a structured array (possibly for use as an argument list?) but then it is possible to construct structured arrays using {}
(.e.g. {[1],[2]; [3],[4]}
, so odd that they can't be indexed in a reciprocal manner.