How to create a multidimensional array of fixed dimensions?
11 views (last 30 days)
Show older comments
Mariana on 8 May 2020
Commented: Mariana on 14 May 2020
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! :)
Walter Roberson on 9 May 2020
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.
More Answers (1)
Steven Lord on 8 May 2020
There's no such thing as the -25th column in an array in MATLAB, nor is there such a thing as the 1.5th column.
You can make an array with separate coordinates that you can use like indices (though as usual, be careful when performing exact equality comparisons with == on floating-point numbers. What I wrote below is safe because all the numbers in x and y can be represented exactly in double precision.)
x = (-5:5).';
y = (-3:0.5:3);
z = x.^2 + y.^3;
z(x == -4, y == 1.5) % (-4)^2+(1.5)^3
If you tell us a little more detail about what you're trying to do with this array we may be able to offer alternate suggestions.
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!