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.
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
This code should work fine for any input.
sz = size(input); if any(input(:)) output = doAlg(input); end output = reshape(output,sz);
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.
What techniques have you used to ensure your code works with all array shapes? List them here.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.