# Programming oddities

### From GHER

## Contents |

# Matlab

## ndims

For scalars and vectors, ndims always returns 2.

>> ndims(0) ans = 2

>> ndims([1 2 3 4]) ans = 2

## isvector

>> isvector(1) ans = 1

## structures as matrices

Even structures are matrices:

s.field = 1;

You can index them and query the dimensions (which is also two):

s(1) ndims(s)

So every thing in mat(trix)lab is a matrix; Even function handle (tested in octave):

ismatrix (@(x) x) ans = 1

## datestr

Matlab 7.10.0.499 (R2010a):

>> datestr([1495 1 4 0 0 0]) ans = 03-Feb-0004 01-Jan-0000 04-Jan-0000 00-Jan-0000 00-Jan-0000 00-Jan-0000 >> datestr([1495 1 4 0 0 1]) ans = 04-Jan-1495 00:00:01

What happened the 4th January 1495? But then:

>> datestr([1495 1 5 0 0 0]) ans = 05-Jan-1495

# Appending data to an empty array

For a vector is works as expected:

>> A = []; >> A(end+1) = 1 A = 1 >> whos A Name Size Bytes Class Attributes A 1x1 8 double

However, for a 3d-array, we get 2 elements (instead of 1) in matlab R2013a.

>> A = []; >> A(1,1,end+1) = 1; A(:,:,1) = 0 A(:,:,2) = 1 >> whos A Name Size Bytes Class Attributes A 1x1x2 16 double

# Python

## sqrt is also calculated on mask value in a Masked array

In numpy version 1.6.1, numpy.sqrt is also applied to masked values and returns a warning if these are negative:

import numpy norm2 = numpy.ma.array([1, -2, 3], mask = [0, 1, 0]) numpy.sqrt(norm2) /usr/bin/ipython:1: RuntimeWarning: invalid value encountered in sqrt

This behavior is inconsistent since the ** operators applies only on non-masked value:

b = ma.array([1, -2, 3], mask = [0, 1, 0]) b2 = b**2 b2.data Out[5]: array([ 1, -2, 9])

Thus numpy.sqrt(b**2) returns this warning.

A work-around:

valid = numpy.logical_not(norm2.mask) norm2[valid] = numpy.sqrt(norm2[valid])

## Numpy: arr.max() can return NaN

Numpy's max can return a NaN as maximum value:

In [1]: array([1.,NaN]).max() Out[1]: nan

Unlike python building max function:

In [10]: max([1.,NaN]) Out[10]: 1.0

Also unlike Fortran and Matlab. For a sane behaviour on should use numpy.nanmax().

# Shell

i=010 let i=$i+1 echo $i 9