Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top