How to index first element of an arbitary sized matrix?

조회 수: 1 (최근 30일)
Joseph Hansen-Shearer
Joseph Hansen-Shearer 2023년 11월 8일
댓글: Stephen23 2023년 11월 8일
I have a matrix and I need to index the first dimension but I don't know the size of the matrix. Is there a way to do this in a generic way rather than hard code each case. I am aware I could do this with eval but I try and steer clear of using this function where possible.
Example:
ind_left = 25;
ind_right = 66;
% For a 2-D matrix it would be this
A = rand(100,100); % sample 3-D input matrix
B = A(ind_left:ind_right,:);
% For a 3-D matrix it would
A = rand(100,100,100); % sample 3-D input matrix
B = A(ind_left:ind_right,:,:);
% For a 4-D matrix it would be ...
  댓글 수: 3
Joseph Hansen-Shearer
Joseph Hansen-Shearer 2023년 11월 8일
This is an even neater solution. Although shouldn't it be
C = repmat({':'},ndims(A),1);
Stephen23
Stephen23 2023년 11월 8일
@Joseph Hansen-Shearer: thank you for noticing that, I fixed my comment!

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

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 11월 8일
편집: Dyuman Joshi 2023년 11월 8일
%Example
ind_left = 25;
ind_right = 45;
vec = ind_left:ind_right;
n = 5;
A = rand(50*ones(1,n)); % sample n-D input matrix
size(A)
ans = 1×5
50 50 50 50 50
%Manually
B = A(vec,:,:,:,:);
size(B)
ans = 1×5
21 50 50 50 50
%Generalised method
C = reshape(A(vec,:),[numel(vec) size(A, 2:ndims(A))]);
size(C)
%Check for equality
isequal(B,C)
ans = logical
1
  댓글 수: 3
Dyuman Joshi
Dyuman Joshi 2023년 11월 8일
You are welcome!
Joseph Hansen-Shearer
Joseph Hansen-Shearer 2023년 11월 8일
For other people looking the answer by @Stephen23 is neater

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by