For loop over each dimension of a n-dimensional matrix
1 回表示 (過去 30 日間)
古いコメントを表示
I am trying to use a 1:n vector to populate a n-dimensional matrix. The matrix should describe the sum of some of the elements of the vector. For example, for n=4, myMatrix(1,1,2,2) is the sum of the third and fourth element of the vector, myMatrix(2,2,2,2) is the sum of all of the elements of the vector, etc.
The following works for n=4 elements, but I am not sure how to write it as a loop, and for an arbitrary number n.
n=4;
myVector = normrnd(0,1,[1,n]); % Get a vector of n random numbers
myMatrix = zeros(ones(1,n)*2); % Initiate the 2x2x2x2 matrix
myMatrix(2,:,:,:) = myMatrix(2,:,:,:) + myVector(1)
myMatrix(:,2,:,:) = myMatrix(:,2,:,:) + myVector(2)
myMatrix(:,:,2,:) = myMatrix(:,:,2,:) + myVector(3)
myMatrix(:,:,:,2) = myMatrix(:,:,:,2) + myVector(4)
Many thanks if you are able to help with this!
0 件のコメント
採用された回答
DGM
2021 年 4 月 28 日
Something like this:
n = 4;
myVector = normrnd(0,1,[1,n]); % Get a vector of n random numbers
myMatrix = zeros(ones(1,n)*2); % Initiate the 2x2x2x2 matrix
for d = 1:n
% this is building the list of indexing expressions
idx = repmat({':'},[1 n]); % this is :,:,:,...
idx{d} = 2;
% then you can use them like so
myMatrix(idx{:}) = myMatrix(idx{:}) + myVector(d)
end
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!