Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that all entries in a cell array have the same size?

Tags:

matlab

I have a cell array C that whose elements are n-dimensional numeric arrays. For example:

C = {[111 121 131; 211 221 231], ...
     [112 122 132; 212 222 232], ...
     [113 123 133; 213 223 233], ...
     [114 124 134; 214 224 234]};

I'm looking for a convenient way to test that they all the nd-arrays in C have the same shape (as reported by the size function).

The criterion for equality here is not entirely trivial. Depending on the situation one may want to regard a shape of [2 3 4] different from or equal to a shape of, say, [1 2 3 4] or [2 1 3 1 4].

For my immediate purposes I want to treat [2 3 4] as different from [1 2 3 4], etc.

(BTW: order always matters; e.g., [2 3 4] is never equal to [4 3 2], say.)

I tried several things (such as, getting the length of unique(C)), but they all fail... (After almost two years of use, my MATLAB instincts remain close to null.)

like image 767
kjo Avatar asked Feb 14 '14 13:02

kjo


1 Answers

Test the size of each cell of C against the size of one cell, for example the first. For testing equality of sizes you need isequal (== won't do because the sizes of the sizes may be different).

all(cellfun(@(e) isequal(size(C{1}), size(e)) , C(2:end)))

If you want to consider a size [2 3 4] equal to [1 2 3 4] etc, just add squeeze:

size1 = size(squeeze(C{1}));
all(cellfun(@(e) isequal(size1, squeeze(size(e))) , C(2:end)))
like image 170
Luis Mendo Avatar answered Sep 25 '22 23:09

Luis Mendo