How to generate a multi-dimensional array from a vector ?
2 views (last 30 days)
Show older comments
If I have a vector and a parameter m, I need to generate a m-dimensional array , where X is defined as follows:
where , ⋯, .
How do I write this code?
0 Comments
Accepted Answer
Steven Lord
on 21 Jun 2022
Let's make the 5-by-5-by-5 multiplication table.
x = (1:5).';
maxdim = 3;
% Initialize the result to the vector itself
result = x;
n = numel(x);
for dim = 2:maxdim
newsize = ones(1, dim);
newsize(dim) = n;
% Reshape x to be a 1-by-1-by-...-by n array and use implicit expansion
result = result .* reshape(x, newsize);
end
result
More Answers (2)
Karim
on 20 Jun 2022
Edited: Karim
on 20 Jun 2022
see below for an example. i used several for loops for sake of readability
% pick the numer of dimensions e.g. 4
M = 4;
% generate 'small x' with 'M' random numbers
x = rand(M,1);
% allocate 'big X', repeat 'M' as many times as you have dimensions
X = zeros(M,M,M,M);
% loop over each dimension
for i1 = 1:M
for i2 = 1:M
for i3 = 1:M
for im = 1:M
% compute the value
X(i1, i2, i3, im) = x(i1) * x(i2) * x(i3) * x(im) ;
end
end
end
end
% have a look at the dimensions of X
size(X)
DGM
on 20 Jun 2022
Edited: DGM
on 20 Jun 2022
I'm sure there are more elegant ways, but here's this. I'm pretty sure it works.
% inputs
m = 3;
x = [1 2 3 4 5 6 7 8 9];
idxmax = floor(sqrt(numel(x))); % assuming the arrays are square
X = 1; % initialize
% build base index array for dim 1:2
idx0 = repmat((1:idxmax).',[1 repmat(idxmax,[1 m-1])]);
idxn = idx0; % work on a copy of the index array
for km = 1:m
X = X.*x(idxn); % partial product
% permute the index array
if km<m
thisdv = 1:m;
thisdv([1 km+1]) = thisdv([km+1 1]);
idxn = permute(idx0,thisdv);
end
end
X
Note that the index array is 2D. Instead of trying to create N-D index arrays, the output X grows by implicit expansion during multiplication.
See Also
Categories
Find more on Matrices and Arrays 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!