matrix indexing all indexes except one
조회 수: 8 (최근 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.)
댓글 수: 0
채택된 답변
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개)
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!