How to generate a multi-dimensional array from a vector ?
Afficher commentaires plus anciens
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?
Réponse acceptée
Plus de réponses (2)
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)
1 commentaire
shuang Yang
le 21 Juin 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.
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!