How do I subtract variable dimension arrays

Right now I do this:
dx = dists(2:end,1,:) - dists(1:end-1,1,:);
dy = dists(2:end,2,:) - dists(1:end-1,2,:);
dz = dists(2:end,3,:) - dists(1:end-1,3,:);
where:
>>size(dists)
ans =
13 9 1159
I would like to do this where dists could be (13,9,1159,8) or an arbitrarily larger dimensions tacked on to the end. The two arrays I'm subtracting would always be the same size and the same particular slices would be subtracted. (as you can see, I'm just subtracting the 1st from 2nd, 2nd from 3rd, etc along three columns in three vector calcs)
How would I specify that for arbitrarily larger dimensions instead of an if statement on size and then ':', or ':,:', or ':,:,:', etc.?

 채택된 답변

Sean de Wolski
Sean de Wolski 2013년 10월 1일

0 개 추천

Use diff specifying the dimension:
dists = rand(100,4,23);
drow = diff(dists,1,1); %rows first dimension
dcol = diff(dists,1,2); %column second dimension
dpage = diff(dists,1,3); %pages third dimension
Now you could just loop over the dimensions and store the results in a cell array.

댓글 수: 1

Kevin
Kevin 2013년 10월 1일
That worked perfectly! I wasn't familiar with diff but thanks to you, now I am.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

태그

질문:

2013년 10월 1일

댓글:

2013년 10월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by