MATLAB: How to create a multidimensional array of fixed dimensions

MATLABmultidimensional array

I would like to create an array in 4 dimensions. Each dimension has a fixed size.
x =0 to 200 –>step 1
y =-25 to 25 –> step 0.5
z = 0 to 180 –> step 1
h = -10 to 10 –> step 0.1
The idea behind is to save one value on a specifc position.
For example if I have an input array [30,-0.5,100,2 ] = 21
At that location I want to save the value.
At a specific amount I would like to read the values inside this array.
Hope you can help me! 🙂

Best Answer

xmin = 0; xmax = 200; xincr = 1;
ymin = -25; ymax = 25; yincr = 0.5;
zmin = 0; zmax = 180; zincr = 1;
hmin = -10; hmax = 10; hincr = 0.1;
xvec = xmin : xincr : xmax;
yvec = ymin : yincr : ymax;
zvec = zmin : zincr : zmax;
hvec = hmin : hincr : hmax;
x2xidx = @(xval) round((xval - xmin)/xincr) + 1;
y2yidx = @(yval) round((yval - ymin)/yincr) + 1;
z2zidx = @(zval) round((zval - zmin)/zincr) + 1;
h2hidx = @(hval) round((hval - hmin)/hincr) + 1;
nx = length(xvec);
ny = length(yvec);
nz = length(zvec);
nh = length(hvec);
M = zeros(nx, ny, nz, nh);
%example of use
M(x2xidx(17), y2yidx(-6.5), z2zidx(93), h2hidx(-4) ) = 1;
[XIDX, YIDX, ZIDX, HIDX] = ind2sub(size(M), find(M));
disp([XIDX, YIDX, ZIDX, HIDX])
disp([xvec(XIDX), yvec(YIDX), zvec(ZIDX), hvec(HIDX)])
You can store by index or you can use the helper functions to convert numeric value to index.