matrix indexing all indexes except one

4 views (last 30 days)
I have got a n^m matrix which changes for every look and would like to store this sequence of matrices. I don't know by default what will be m and n. Something like YY(:,:,:,:,j)=Y; or YY(:,:,:,j)=Y; if the dimension would be known in forehand. Thank you very much. (Note that in the example is the dimension of Y first 4 and the 3.)

Accepted Answer

Steven Lord
Steven Lord on 1 Nov 2017
So you're not sure what ndims will be for the arrays that you want to store? In that case the most straightforward approach is probably going to be a cell array. You can even use a cell array to store data of different size and/or number of dimensions.
c = cell(1, 4);
for z = 1:4
c{z} = rand(repmat(z, 1, z));
end
size(c{4}) % [4 4 4 4]
If you're sure all of your arrays will be the same size and number of dimensions, even if you're not sure what those are at the start, you can do this.
numToStore = 7;
% You find this out when you create the first array to be stored
arraySize = [4 5 3];
dim = numel(arraySize);
storeInDimension = dim+1;
preallocSize = [arraySize numToStore];
result = zeros(preallocSize);
% The trick
indexExpression = [repmat({':'}, 1, dim) 1];
for k = 1:numToStore
indexExpression{storeInDimension} = k;
result(indexExpression{:}) = k*ones(arraySize);
end
This "trick" works in kind of a similar way as described in the "Function Call Arguments" section on this documentation page. As described on the documentation page for subsref:
"The syntax A(1:2,:) calls B = subsref(A,S) where S is a 1-by-1 structure with S.type='()' and S.subs={1:2,':'}. The colon character ':' indicates a colon used as a subscript."
  1 Comment
Rafael Schwarzenegger
Rafael Schwarzenegger on 2 Nov 2017
Edited: Rafael Schwarzenegger on 2 Nov 2017
Dear Steven, thank you. Exactly ndims isn't sure. This looks very good. It solves the problem. You saved my code!

Sign in to comment.

More Answers (1)

KSSV
KSSV on 1 Nov 2017
YOu can initialize it by using [] in-place of dimensions. Check the below code:
a = zeros([],[]) ;
for i = 1:10
for j = 1:5
a(i,j) = rand ;
end
end
  1 Comment
Rafael Schwarzenegger
Rafael Schwarzenegger on 1 Nov 2017
Edited: Rafael Schwarzenegger on 1 Nov 2017
Thank you very much for your answer. Well, I would need it for a general dimension. Your solution is for the dimension 2 (normal matrix). My problem is not, that I don't want to allocate memory in forehand. I would like not to need to change the code, when I am dealing with a matrix or a "cube".

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!