Home > MATLAB > Counting the number of dimensions

Counting the number of dimensions

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);
end

nntdims(1)        % 0
nntdims(1:5)      % 1
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: