loop through structures and find the correlation

조회 수: 8 (최근 30일)
Richard
Richard 2012년 2월 27일
The following example resembles a similar problem that I'm dealing with, although the code below is merely an example, it is structured in the same format as my actual data set.
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)))];
So, this script would show the correlation between pairs of Air Temperature of 4 locations. I'm looking for a way of also looking at the correlation between 'SolRad' and 'Rain' between the locations (same process as for AirT) or any variables denoted in the structure. I could do this by replacing the inputs into 'Data' but this seems rather long winded especially when involving many different variables. Any ideas on how to do this? I've tried using a loop but it seems harder than I though to try and get the data into the same format as the example.

채택된 답변

Oleg Komarov
Oleg Komarov 2012년 2월 27일
I would do it slightly differently:
fakeData = @(location) struct('Location',location,'AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1));
s(1) = fakeData('England');
s(2) = fakeData('Wales');
s(3) = fakeData('Scotland');
s(4) = fakeData('Ireland');
Repeating your example:
FieldName = {s.Location};
R = corrcoef([s.AirT],'rows','pairwise');
Going further (SolRad vs Rain):
R = corrcoef([[s.SolRad] [s.Rain]],'rows','pairwise');
You're interested in matrix R(1:4,5:end)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by