boucle sur toutes les combinaisons possibles
-
27-10-2019 - |
Question
Je voudrais inclure une boucle dans mon script qui trouve la corrélation de toutes les combinaisons possibles des données. Cela peut être fait manuellement par le code suivant:
clear all
%generate fake data
LName={'Name1','Name2','Name3'};
Data={rand(12,1),rand(12,1),rand(12,1)};
%place in a structure
d = [LName;Data];
Data = struct(d{:});
%find the correlation
[R,P] = corrcoef(Data.Name1,Data.Name2);
[R2,P2] = corrcoef(Data.Name1,Data.Name3);
[R3,P3] = corrcoef(Data.Name2,Data.Name3);
Cependant, je voudrais faire cela dans une boucle, j'ai commencé, mais ai échoué au premier obstacle. Ma boucle tentative, ce qui ne fonctionne pas est illustré ci-dessous:
SNames=fieldnames(Data);
for i=1:numel(SNames);
[R{i},P{i}] = corrcoef(Data.(SNames{i}),Data.(SNames{i+1}));
end
Je me bats pour savoir comment dire Matlab boucle sur une combinaison différente de valeurs à chaque itération.
Toute aide fournie serait très apprécié.
La solution
Try something like this:
pairs = combnk (1:3,2) % all combinations of 2 elements taken out of the vector [1,2,3]
for i = 1 : size (pairs,1)
[R{i},P{i}] = corrcoef(Data.(SNames{pairs(i,1)}),Data.(SNames{pairs(i,2)}));
end
Autres conseils
@ItamarKatz answer is a good one. However, if you don't have the statistics toolbox, you can not use the combnk command.
In that case, you can download combinations generator from here.