Subtract combinations of variables in a vector

7 ビュー (過去 30 日間)
Stephanie Nykamp
Stephanie Nykamp 2011 年 5 月 17 日
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 日
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 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 5 月 17 日
+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 日
Another approach:
S = -diff(nchoosek(vec,2),[],2)

Paulo Silva
Paulo Silva 2011 年 5 月 17 日
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 日
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));

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by