1

I would like to include a loop in my script which finds the correlation of every possible combination of the data. This can be done manually by the following code:

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);

However, I would like to do this in a loop, I have started but have failed at the first hurdle. My attempted loop, which doesn't work is shown below:

SNames=fieldnames(Data);
for i=1:numel(SNames);
    [R{i},P{i}] = corrcoef(Data.(SNames{i}),Data.(SNames{i+1}));
end

I'm struggling on knowing how to tell matlab to loop over a different combination of values with every iteration.

Any help provided would be much appreciated.

user1053544
  • 107
  • 4
  • 11

2 Answers2

2

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
Itamar Katz
  • 9,544
  • 5
  • 42
  • 74
  • works perfectly. However, for future reference, can the line pairs = combnk (1:3,2) be used differently i.e. if you want to find the correlation between 3 elements you would change this line to pairs = combnk (1:3,3)? thanks for your help – user1053544 Jan 11 '12 at 16:07
  • yes, but picking 3 elements out of 3 possible indices has only one possibility (1,2,3). And, what is correlation between 3 elements...? – Itamar Katz Jan 12 '12 at 09:04
  • So, from the solution provided above how would it be possible to adapt this to store an output of all possible combinations of the elements i.e. not only all combinations of 2 elements but to store all combinations of 2 elements and of 3 elements... and so on, depending on the size of the data set. – user1053544 Jan 12 '12 at 11:54
1

@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.

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104