matrix indexing all indexes except one

조회 수: 8 (최근 30일)
Rafael Schwarzenegger
Rafael Schwarzenegger 2017년 11월 1일
편집: Rafael Schwarzenegger 2017년 11월 2일
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일
편집: 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일
편집: 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에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by