필터 지우기
필터 지우기

How to gracefully truncate a matrix of unknown dimensions?

조회 수: 5 (최근 30일)
Disciple of the Forbidden Spell
Disciple of the Forbidden Spell 2019년 7월 13일
댓글: Bruno Luong 2019년 7월 14일
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?

답변 (1개)

Bruno Luong
Bruno Luong 2019년 7월 13일
편집: Bruno Luong 2019년 7월 13일
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
Tmfu Vh
Tmfu Vh 2019년 7월 14일
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 2019년 7월 14일
No you can't use 'end' in commalist, you have to replace it with
size(Input,Dimension)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by