How to gracefully truncate a matrix of unknown dimensions?

7 vues (au cours des 30 derniers jours)
Disciple of the Forbidden Spell
Commenté : Bruno Luong le 14 Juil 2019
Suppose here comes a
function Truncated=MatrixTruncate(Input,Dimension,a,b)
Input is a matrix, whose dimension is unknown and depends on the caller. This function will truncate the matrix along the dimension Dimension, from index a to b. Now I use eval to generate code at runtime:
Truncated=eval(['Input(' repmat(':,',1,Dimension-1) num2str(a) ':' num2str(b) repmat(',:',1,ndims(Input)-Dimension) ')']);
Personally I feel the code somewhat unnatural, though it did work. Are there any more graceful solutions?

Réponses (1)

Bruno Luong
Bruno Luong le 13 Juil 2019
Modifié(e) : Bruno Luong le 13 Juil 2019
Input = rand(3,4,5)
Dimension = 2;
a=2; b=4;
commaidx = cell(size(size(Input)));
commaidx(:) = {':'};
commaidx{Dimension} = a:b;
Truncated = Input(commaidx{:})
  7 commentaires
Tmfu Vh
Tmfu Vh le 14 Juil 2019
Splendid solution. What if I want to use the "end" index here?
commaidx{Dimension} = a:end;
This code is not allowed.
Bruno Luong
Bruno Luong le 14 Juil 2019
No you can't use 'end' in commalist, you have to replace it with
size(Input,Dimension)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by