Substract nd array slices

조회 수: 2 (최근 30일)
Orangelynx
Orangelynx 2017년 11월 12일
댓글: Orangelynx 2017년 11월 13일
Hi,
I have a n-dimensional array which may contain singleton dimensions and I would like to substract the second page of dimension i from the first page of dimension i. My current solution looks something like this:
function A = substract_page( A, dim )
orig_size = size(A); % store the original shape
A = shiftdim(A, dim); % shift the dimension to be substracted to the end
shifted_size = size(A); % aliter: shifted_size = circshift orig_size(dim); ?
A = reshape(A, [], shifted_size(end)); % collapse first dimensions for easier substraction
A = A(:, 2) - A(:, 1);
shifted_size(end) = shifted_size(end) - 1; % substraction leads to dimension loss
A = reshape(A, shifted_size); % restore shape
lost_dimensions = length(orig_size) - ndims(A);
A = shiftdim(A, -lost_dimensions); % make sure that singular dimensions in the end don't get lost
A = shiftdim(A, length(orig_size) - dim + lost_dimensions); % restore order
end
But it seems way to complicated and I feel there is a much easier and more elegant solution.

채택된 답변

Jan
Jan 2017년 11월 12일
편집: Jan 2017년 11월 12일
Does your code perform this:
dim = 3;
A = rand(2,3,4,5);
A = A(:, :, 2, :) - A(:, :, 1, :)
? Then:
function A = substract_page(A, dim)
C1 = repmat({':'}, 1, ndims(A));
C2 = C1;
C1{dim} = 1;
C2{dim} = 2;
A = A(C2{:}) - A(C1{:});
end
  댓글 수: 3
Jan
Jan 2017년 11월 13일
@Orangelynx: When the dimension to operate on has the length 2, diff is perfect. My code would be useful only, if the input has e.g. the length 4 as in my example, and only the difference between the first 2 slices should be calculated ignoring the rest.
Orangelynx
Orangelynx 2017년 11월 13일
good point, I guess I didn't specify that clearly in my original question.

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

추가 답변 (1개)

Matt J
Matt J 2017년 11월 12일
Not sure, but maybe you are looking for
A=diff(A,1,dim);
  댓글 수: 1
Orangelynx
Orangelynx 2017년 11월 13일
wow.. I knew about diff, but for some reason my head told me it's not what I was looking for, eventhough with the dim parameter, it's exactly what I wanted... thanks.

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

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by