How to generate a multi-dimensional array from a vector ?
이전 댓글 표시
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?
채택된 답변
추가 답변 (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)
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.
댓글 수: 1
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!