Subtract combinations of variables in a vector
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
Accepted Answer
More Answers (3)
Matt Fig
on 17 May 2011
Another approach:
S = -diff(nchoosek(vec,2),[],2)
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
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));
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!