For loop over each dimension of a n-dimensional matrix

1 回表示 (過去 30 日間)
David Mao
David Mao 2021 年 4 月 28 日
コメント済み: David Mao 2021 年 4 月 28 日
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!

採用された回答

DGM
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
  1 件のコメント
David Mao
David Mao 2021 年 4 月 28 日
This is amazing, I did not know it was possible to index like that! Thank you so much!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by