For loop over each dimension of a n-dimensional matrix

1 view (last 30 days)
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!

Accepted Answer

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

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!