循环结构并找到相关性

时间:2012-02-27 16:00:58

标签: matlab structure correlation

以下示例类似于我正在处理的类似问题,虽然下面的代码仅仅是一个示例,但它的结构格式与我的实际数据集相同。

clear all

England = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));
Wales = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));
Ireland = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));
Scotland = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));

Location = struct('England',England,'Wales', Wales, 'Ireland',Ireland,'Scotland',Scotland);

FieldName={'England','Wales','Scotland','Ireland'};
Data = {England.AirT,Wales.AirT,Scotland.AirT,Ireland.AirT};
Data = [FieldName;Data];
Data = struct(Data{:});
Data = cell2mat(struct2cell(Data)');
[R,P] = corrcoef(Data,'rows','pairwise');
R_Value= [FieldName(nchoosek(1:size(R,1),2)) num2cell(nonzeros(tril(R,-1)))];

因此,该脚本将显示4个位置的气温对之间的相关性。我正在寻找一种方法来查看位置之间的'SolRad'和'Rain'之间的相关性(与AirT相同的过程)或结构中表示的任何变量。我可以通过将输入替换为“数据”来实现这一点,但这似乎相当长,特别是涉及许多不同的变量时。关于如何做到这一点的任何想法?我尝试过使用循环,但它似乎比我尝试将数据转换为与示例相同的格式更难。

2 个答案:

答案 0 :(得分:1)

让我们看看这是否有帮助,或者你在想什么:

clear all

England = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));
Wales = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));
Ireland = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));
Scotland = struct('AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));

Location = struct('England',England,'Wales', Wales, 'Ireland',Ireland,'Scotland',Scotland);

% get all the location fields
FieldName = transpose(fieldnames(Location));
% get the variables recorded at the first location
CorrData = fieldnames(Location.(FieldName{1}));
% get variables which were stored at all locations(just to be safe,
% we know that they are all the same)
for ii=2:length(FieldName)
  CorrData = intersect(CorrData,fieldnames(Location.(FieldName{ii})));
end

% process each variable that was recorded
for ii=1:length(CorrData)
  Data = cell(1,length(FieldName));
  % get the variable data from each location and store in Data
  for jj=1:length(FieldName)
    Data{jj} = Location.(FieldName{jj}).(CorrData{ii});
  end
  % process the data
  Data = [FieldName;Data];
  Data = struct(Data{:});
  Data = cell2mat(struct2cell(Data)');
  [R,P] = corrcoef(Data,'rows','pairwise');
  R_Value= [FieldName(nchoosek(1:size(R,1),2)) num2cell(nonzeros(tril(R,-1)))];
  % display the data, sounds good right?
  fprintf(1,'Correlation for %s\n',CorrData{ii});
  for jj=1:size(R_Value,1)
    fprintf(1,'%s\t%s\t%f\n',R_Value{jj,1},R_Value{jj,2},R_Value{jj,3});
  end
end

让我知道,如果我误解了,或者这比你想的更多。谢谢!

答案 1 :(得分:0)

fieldnames(s)和dynamic field references是你的朋友。

我建议做一个结构,其中'name'是一个字段,其他字段是你想要的。无论您如何设置structure s,都可以使用fn = fieldnames(s);返回字段的单元格数组。您可以使用包含名称的变量周围的括号来使用这些名称访问结构的内容。

fn = fieldnames(s);
for i=1:length(fn)
disp([fn{i} ':' s.(fn{i})]
end

当然,无论你对价值观做什么都取决于你!