Subtract combinations of variables in a vector
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Matt Tearle
on 17 May 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 Comments
Matt Tearle
on 17 May 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).
More Answers (3)
Paulo Silva
on 17 May 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
0 Comments
Andrei Bobrov
on 17 May 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 Comment
Matt Fig
on 17 May 2011
I believe the last line should be:
vdistt = -Mdist(tril(true(size(Mdist)),-1));
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!