循环所有可能的组合 [英] loop over all possible combinations

查看:107
本文介绍了循环所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的脚本中包含一个循环,该循环查找数据的每种可能组合的相关性.可以通过以下代码手动完成此操作:

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

我正在努力了解如何告诉matlab每次迭代都循环使用不同的值组合.

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.

推荐答案

尝试如下操作:

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

这篇关于循环所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆