Subtract combinations of variables in a vector

I have a vector of 7 variables and I need to subtract the all possible combinations of one variable from another. I have tried to loop through the variables but I only get the first variable minus all the rest. I need the loop to continue to subtract variable 2 from the rest. Any help would be greatly appreciated.
for c=1:6; DER1(:,c)=DER(c); DER2(:,c)=DER(c+1);
for d=1:20;
DED(:,d) = DER1(c)-DER2(c);
end
end

 채택된 답변

Matt Tearle
Matt Tearle 2011년 5월 17일

0 개 추천

If you have Statistics Toolbox, here's a neat trick (I think this is what you're asking for):
% make a vector of numbers
vec = rand(7,1)
% get inter-point "distances"
dfun = @(x,y) x-y;
pdist(vec,dfun)
% or if you prefer
squareform(pdist(vec,dfun))
EDIT TO ADD
As Teja suggested:
% as a matrix
bsxfun(@minus,vec',vec)
% as a vector
squareform(bsxfun(@minus,vec',vec))

댓글 수: 4

This also works:
bsxfun(@minus,vec,vec')
But I too like the PDIST function. It is a very handy (and REALLY REALLY FAST) function for getting various distances on multidimensional data.
+1 for bsxfun!
Matt Tearle
Matt Tearle 2011년 5월 17일
I thought the OP wanted a vector as a result, so I thought pdist was the better candidate. But after thinking about the bsxfun solution, I realized you can always use squareform to go back to a vector. So... (see edit).

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

추가 답변 (3개)

Matt Fig
Matt Fig 2011년 5월 17일

1 개 추천

Another approach:
S = -diff(nchoosek(vec,2),[],2)
Paulo Silva
Paulo Silva 2011년 5월 17일

0 개 추천

Here's a version with two for loops
v=1:7;
for a=1:7
for b=1:7
%comment the next line if you want the variable to be divided by itself
if a~=b
v(b)=v(b)-v(a);
%comment the next line if you want the variable to be divided by itself
end
end
end
v
Andrei Bobrov
Andrei Bobrov 2011년 5월 17일

0 개 추천

more variant (without Statistics Toolbox)
[I J] = meshgrid(vec);
Mdist = reshape(diff([I(:) J(:)],[],2),[],length(vec));
Vdistt = -Mdist(tril(Mdist)~=0);
MORE variant: first vector, then the matrix
[I J] = meshgrid(vec);
V1 = I(:) - J(:);
[~, b] = unique(abs(V1));
Vdist2 = sortrows([V1(b) b],2);
Mdist2(tril(true(length(vec)),-1)) = -Vdist2(1:end-1,1);
Mdist2 = Mdist2 - Mdist2.';

댓글 수: 1

Matt Fig
Matt Fig 2011년 5월 17일
I believe the last line should be:
vdistt = -Mdist(tril(true(size(Mdist)),-1));

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by