For loop over each dimension of a n-dimensional matrix

1 vue (au cours des 30 derniers jours)
David Mao
David Mao le 28 Avr 2021
Commenté : David Mao le 28 Avr 2021
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!

Réponse acceptée

DGM
DGM le 28 Avr 2021
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 commentaire
David Mao
David Mao le 28 Avr 2021
This is amazing, I did not know it was possible to index like that! Thank you so much!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by