循环遍历所有可能的组合

发布于 2024-12-25 22:51:34 字数 661 浏览 1 评论 0原文

我想在我的脚本中包含一个循环,它可以找到数据的每种可能组合的相关性。这可以通过以下代码手动完成:

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

但是,我想在循环中执行此操作,我已经开始但在第一个障碍时失败了。我尝试的循环如下所示,但不起作用:

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

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

任何提供的帮助将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘香 2025-01-01 22:51:34

尝试这样的事情:

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

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
苍风燃霜 2025-01-01 22:51:34

@ItamarKatz 的答案很好。但是,如果您没有统计工具箱,则无法使用combnk命令。
在这种情况下,您可以从此处下载组合生成器

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文