Archive for November, 2010

Counting the number of dimensions

6th November, 2010 Leave a comment

Knowing how many dimensions your array has is important, if only to know that your pie chart really is 4d. MATLAB is a little odd in that scalar values are, under the bonnet, matrices with one row and one column. Likewise, vectors are matrices with one dimension of length one. Mostly, you don’t notice this but when you are trying to count the number of dimensions, you can see some odd results.

ndims(1)        % 2
ndims(1:5)      % 2

Often, you may prefer to know the number of nontrivial dimensions: that is, how many dimensions an array has that have length greater than one. I noticed this problem while browsing the code of the rather excellent xml_io_tools by Jarek Tuszynski. The solution is easy to wrap into a function.

function n = nntdims(x)
%NNTDIMS Number of non-trivial dimensions.
   n = nnz(size(x) > 1);

nntdims(1)        % 0
nntdims(1:5)      % 1

Get every new post delivered to your Inbox.

Join 248 other followers