For loop over each dimension of a n-dimensional matrix
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!