matrix indexing all indexes except one
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Rafael Schwarzenegger
le 1 Nov 2017
Modifié(e) : Rafael Schwarzenegger
le 2 Nov 2017
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 commentaires
Réponse acceptée
Steven Lord
le 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 commentaire
Plus de réponses (1)
KSSV
le 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 commentaire
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!