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

 Respuesta aceptada

Matt Tearle
Matt Tearle el 17 de Mayo de 2011
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 comentarios

Teja Muppirala
Teja Muppirala el 17 de Mayo de 2011
This also works:
bsxfun(@minus,vec,vec')
Teja Muppirala
Teja Muppirala el 17 de Mayo de 2011
But I too like the PDIST function. It is a very handy (and REALLY REALLY FAST) function for getting various distances on multidimensional data.
Sean de Wolski
Sean de Wolski el 17 de Mayo de 2011
+1 for bsxfun!
Matt Tearle
Matt Tearle el 17 de Mayo de 2011
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).

Iniciar sesión para comentar.

Más respuestas (3)

Matt Fig
Matt Fig el 17 de Mayo de 2011
Another approach:
S = -diff(nchoosek(vec,2),[],2)
Paulo Silva
Paulo Silva el 17 de Mayo de 2011
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 el 17 de Mayo de 2011
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 comentario

Matt Fig
Matt Fig el 17 de Mayo de 2011
I believe the last line should be:
vdistt = -Mdist(tril(true(size(Mdist)),-1));

Iniciar sesión para comentar.

Categorías

Más información sobre Get Started with MATLAB en Centro de ayuda y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by