matrix indexing all indexes except one

3 次查看(过去 30 天)
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.)

采纳的回答

Steven Lord
Steven Lord 2017-11-1
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 个评论
Rafael Schwarzenegger
编辑:Rafael Schwarzenegger 2017-11-2
Dear Steven, thank you. Exactly ndims isn't sure. This looks very good. It solves the problem. You saved my code!

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2017-11-1
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 个评论
Rafael Schwarzenegger
编辑:Rafael Schwarzenegger 2017-11-1
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".

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by