Matlab: non-integers or numbers below 1 as indices; numbers as field names

117 Views Asked by At

Matlab has limitations in terms of how things can be numbered/indexed:

However, it might be common/appropriate/intuitive to number certain things using zero or negative numbers or non-integer numbers.

For example, storing more and more so-called spherical harmonics requires increasingly negative "indices".

Scaling and shifting those "indices" such that they are natural numbers, i.e. valid (cell-)array indices, has disadvantages (smaller negative indices or finer non-integer indices might appear later, requiring a recomputation of the scale or shift parameters and adjustment of the entire data structure; understanding the resulting data structure requires knowing the scale and shift parameters and requires "mental math" while looking at the data).

Is there a way without these disadvantages?

3

There are 3 best solutions below

1
root On

Numbers can be turned into valid field names for structure arrays for example using this function:

% Field names of Matlab structures:
%  - can't start with a digit, so we prepend 'number_',
%  - can't contain '-', so we replace it by 'minus',
%  - can't contain '+', so we replace it by 'plus' (for numbers such as -1e+20),
%  - can't contain '.', so we replace it by 'point'.
% For example, the number -0.5 turns into the string 'number_minus0point5'.
num2fieldname = @(x)(['number_' replace(replace(replace(num2str(x),'-','minus'),'.','point'),'+','plus')]);

For example, num2fieldname(-1.5e+20) yields 'number_minus1point5eplus20'.

To use them as field names, here for example using the "index" (2,-1):

mystructure.(num2fieldname(2)).(num2fieldname(-1)) = myobject

It won't work if rounding settings for num2str change.

4
root On

containers.Map might achieve what you want. Apparently it can store any objects as values. That seems to be undocumented.

0
Edric On

In recent versions of MATLAB, the table data type allows arbitrary text as variable names.