How do you crop a Matrix?

조회 수: 101 (최근 30일)
zephyr21
zephyr21 2016년 6월 24일
답변: Jos (10584) 2017년 12월 1일
I have a 770x770 matrix that I want to cut down to a 324x324 matrix. How would I cut off the bottom 446 rows and rightmost 446 columns?

답변 (2개)

Jos (10584)
Jos (10584) 2017년 12월 1일
You mean the number of dimensions of M is unknown, but Nkeep is known? Use subsref:
M = randi(10,4,3,4,5) ; % arbitrary dimensions
Nkeep = 2
S = struct('type','()','subs',{repmat({[1:Nkeep]},1,ndims(M))})
M2 = subsref(M, S)

dpb
dpb 2016년 6월 24일
편집: dpb 2016년 6월 24일
Pretty simply, just save what you want...
Nkeep=324; % size to keep
M=M(1:Nkeep,1:Nkeep);
You can, of course, set the unwanted rows, columns = [], but that takes two steps instead of just one:
M(:,Nkeep+1:end)=[]; % columns for all rows, result is rectangular
M(Nkeep+1:end,:)=[]; % now the rows for remaining columns, result is square now
  댓글 수: 2
Jurgen
Jurgen 2017년 11월 30일
How do you generalize this for N dimensional matrices, assuming unknown or large matrix ndims? The only thing I can think of involves eval.
dpb
dpb 2017년 12월 1일
Not much support for templates and the like in procedural code...you might be able to get creative with sub2ind and friends, but likely if it is truly amorphic data sizes/shapes that must be handled it's likely to come down to eval at the bitter end, agreed.

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by