How to generate a multi-dimensional array from a vector ?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Steven Lord
2022-6-21
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
更多回答(2 个)
Karim
2022-6-20
编辑:Karim
2022-6-20
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
2022-6-20
编辑:DGM
2022-6-20
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!