Loren on the Art of MATLAB

July 6th, 2007

Make Code N-D Safe

I've recently been asked some questions about programming safely to account for N-dimensional data. Techniquest that are tried-and-true for two dimensions don't all scale to N dimensions.

Contents

Code That's Not Recommended

The following code doesn't catch dimensions higher than 2.

 if any(any(input))
     output = doAlg(input);
 end

This code is also not recommended because n will be a scalar even if input has more than 2 dimensions. Depending on what is done in the loop, the output might be the wrong shape/dimension (thanks to Jeremy so I could clarify this).

 [m,n] = size(input);
 for i=1:n
     doSomething;
 end

Code That is Safe for Higher Dimensions

This code should work fine for any input.

 sz = size(input);
 if any(input(:))
     output = doAlg(input);
 end
 output = reshape(output,sz);

Benefits

If you consider N-dimensional input when you write functions, you are less likely to find bugs or wrong answers when you go to use it later.

   * The code is easier to understand without so many any statements.
   * Code is robust to N-dimensional inputs.

Your Advice?

What techniques have you used to ensure your code works with all array shapes? List them here.


Get the MATLAB code

Published with MATLAB® 7.4

4 Responses to “Make Code N-D Safe”

  1. Jeremy replied on :

    Actually, if one calls “[m,n] = size(input)” where input has more than 2 dimensions, n is not a vector. It is simply a product of the remaining dimension sizes.

  2. mark replied on :

    I suppose matlab arrays aren’t tensors. However, has there been any discussion about implementing tensor algebra, or can it be done with dimension arguments? For instance, in some circumstances, one might like to consider the column and row dimensions as both being 1 with a new argument to indicate dual space.

  3. Urs (us) Schwarz replied on :

    there are a few helpers, which should not be discarded and often are very useful for preliminary error checking procedures
    help isempty
    help isscalar
    help isvector
    help ndims
    us

  4. Loren replied on :

    Jeremy-

    You are right about size, of course. But it is still possible that your code, if dependent on n for pre-allocation, for instance, will be incorrect for N-dimensional inputs.

    Urs-

    Thanks for the list.

    –Loren

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Jun: I totally can not believe it, Loren. You are really helpful. Thank you so much, MATLAB master!
  • Loren: Wow folks- Always lots of interest when there’s a quickie to try out! I will only make 2 general...
  • Loren: Jun- ismember is your friend here: >> [aa,ind] = ismember(Array2,Arra y1) aa = 1 1 1 1 1 1 1 ind = 1 2 1 4 4 3...
  • Dan: I like the first way better than the second way. Combining the arrays into one and running any is nice, although...
  • James Myatt: How about I = (a == 0 | b == 0); a(I) = []; b(I) = [];
  • Tunc: Hello Loren, love your blog because of such inspiring and challenging comments to such ’small’...
  • Pekka Kumpulainen: Here is my tradeoff. I usually want to keep the original variables as they are most probably...
  • Iain: Followup: Of course, to allow NaNs (counting them as non-zero): mask = (a~=0) & (b~=0); The mask says “a...
  • Matt Fig: I would usually go with something like this: y = a&b; x = a(y); y = b(y); But I was surprised to find...
  • kk: c=all([a;b]) a(c) a(b)

These postings are the author's and don't necessarily represent the opinions of The MathWorks.