Get all unique combinations of 2 columns from a table

I have a table that has 4 variables, similar to this:
Item1 Item2 Item3 Item4
_____ _____ _____ _____
1 5 7 10
What is the best way to produce the delta of each combination of columns? Ex. Item1 vs Item2, Item1 vs Item3, etc.

 Risposta accettata

V = {'Item1','Item2','Item3','Item4'};
T = table(1, 5, 7 ,10, 'VariableNames',V)
T = 1×4 table
Item1 Item2 Item3 Item4 _____ _____ _____ _____ 1 5 7 10
X = nchoosek(1:numel(V),2);
D = diff(T{:,V}(X),1,2);
Z = cell2table([V(X),num2cell(D)])
Z = 6×3 table
Var1 Var2 Var3 _________ _________ ____ {'Item1'} {'Item2'} 4 {'Item1'} {'Item3'} 6 {'Item1'} {'Item4'} 9 {'Item2'} {'Item3'} 2 {'Item2'} {'Item4'} 5 {'Item3'} {'Item4'} 3

Più risposte (1)

I would look into using the perms function, along with the unique and diff functions.

3 Commenti

I couldn't find a good way to succinctly use perms or unique to get my desired output, but I may just not be well versed enough in MATLAB yet to do so. I was able to come up with a solution that in my opinion solved this rather cleanly:
t = table(1, 5, 7 ,10, 'VariableNames', {'Item1' 'Item2' 'Item3' 'Item4'});
tDelta = table();
varNameStrings = string(t.Properties.VariableNames);
for v1 = varNameStrings
for v2 = varNameStrings(find(varNameStrings==v1):end)
comp = v1+" vs "+v2;
if v1 ~= v2
tDelta.(comp) = diff([t.(v1) t.(v2)]);
end
end
end
disp(t)
Item1 Item2 Item3 Item4 _____ _____ _____ _____ 1 5 7 10
disp(tDelta)
Item1 vs Item2 Item1 vs Item3 Item1 vs Item4 Item2 vs Item3 Item2 vs Item4 Item3 vs Item4 ______________ ______________ ______________ ______________ ______________ ______________ 4 6 9 2 5 3
I was probably trying too hard to make use of the variablenames. Stephen's approach is simpler by using column numbers instead.
T = table(1, 5, 7 ,10, 'VariableNames', {'Item1' 'Item2' 'Item3' 'Item4'});
C = nchoosek(T.Properties.VariableNames,2)
C = 6×2 cell array
{'Item1'} {'Item2'} {'Item1'} {'Item3'} {'Item1'} {'Item4'} {'Item2'} {'Item3'} {'Item2'} {'Item4'} {'Item3'} {'Item4'}
delta = diff([T{1,{C{:,1}}};T{1,{C{:,2}}}])
delta = 1×6
4 6 9 2 5 3
His and yours are both excellent and elegant, thank you!

Accedi per commentare.

Categorie

Prodotti

Release

R2021b

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by