Ok, lets say that I have a code where I can have an array:
A = randi([0,9],4,4);
and I want to access the last two columns and rows:
B = A(2:end,2:end);
Now I have the same thing but with 3 dimensions:
A = randi([0,9],4,4,4);
B = A(2:end,2:end,2:end);
Is there any way that I can write both cases in a single generic one?, I was trying to do something like:
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
B = A( 2*ones(1,n):end); % THIS WONT WORK.
I don't know if I explained what I wan't. Please let me know if you need more precise explanation. Thank you

답변 (2개)

KSSV
KSSV 2018년 10월 22일

0 개 추천

Read about sub2ind
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims);
[I,J] = meshgrid(2:4,2:4) ;
idx = sub2ind(size(A),I,J)' ;
B = A(idx);

댓글 수: 1

Manuel Pena
Manuel Pena 2018년 10월 22일
Would sub2ind work with 3 dimensions? Besides that, your code doesn't solve my problem as you are explicitly using the fact that you know that n = 2, when you do the meshgrid call.

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

Steven Lord
Steven Lord 2022년 2월 4일

0 개 추천

Use a comma-separated list.
n = 2; % or 3 or whatever
dims = 4*ones(1,n);
A = randi([0,9],dims) % Leaving the semicolon off for checking purposes
A = 4×4
9 3 8 7 3 1 6 7 6 1 6 2 0 8 8 4
inds = cell(1, n);
for dim = 1:n
inds{dim} = (size(A, dim))+(-1:0); % [end-1, end] in that dimension
end
B = A(inds{:})
B = 2×2
6 2 8 4

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

태그

질문:

2018년 10월 22일

답변:

2022년 2월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by