I would like to loop through all dimensions of a n-dimensional matrix, but the matrix dimensions are unknown beforehand. Below is an example of generating a matrix of unknown dimensions, if it was a 2D matrix looping over those 2 dimensions. But in fact it could have 1-5 dimensions. Can you think of a good solution?
inputMatrixOfUnknownSize = ones(factor(round(rand(1)*500))); % Example matrix that could have 1 to many dimensions
dimList = size(inputMatrixOfUnknownSize) % List the dimensions
% If it was 2D, here's how we'd loop over those two dimensions...but it isn't necessarily 2D!
for iDim1 = 1:dimList(1) for iDim2 = 1:dimList(2) % Operate on each element. In reality the operation will not be the same for all dimensions.
outputMatrixOfUnknownSize(iDim1,iDim2) = outputMatrixOfUnknownSize(iDim1,iDim2)^2; end end
In my real code, the operation that is performed on each matrix element will depend on the dimension size, so I can't eliminate the loop in the example above.
Best Answer