Tuesday, 15 February 2011

loops - Remove duplicates in correlations in matlab -



loops - Remove duplicates in correlations in matlab -

please see next issue:

p=rand(4,4); i=1:size(p,2) j=1:size(p,2) [r,p]=corr(p(:,i),p(:,j)) end end

clearly, loop cause number of correlations doubled (i.e., corr(p(:,1),p(:,4)) , corr(p(:,4),p(:,1)). have suggestion on how avoid this? perhaps not using loop?

thanks!

i have 4 suggestions you, depending on doing compute matrices. i'm assuming illustration gave simplified version of needs done.

first method - adjusting inner loop index

one thing can alter j loop index goes 1 i. way, lower triangular matrix , concentrate on values within lower triangular half of matrix. upper half set zero. in other words:

for = 1 : size(p,2) j = 1 : %// code here end end second method - leave unchanged, utilize unique

you can go ahead , utilize same matrix did before total 2 for loops, can filter duplicates using unique. in other words, can this:

[y,indices] = unique(p);

y give list of unique values within matrix p , indices give locations of where these occurred within p. note these column major indices, , if wanted find row , column locations of these locations occur, can do:

[rows,cols] = ind2sub(size(p), indices); third method - utilize pdist , squareform

since you're looking solution requires no loops, take @ pdist function. given m x n matrix, pdist find distances between each pair of rows in matrix. squareform transform these distances matrix have seen above. in other words, this:

dists = pdist(p.', 'correlation'); distmatrix = squareform(dists); fourth method - utilize corr method straight out of box

you can utilize corr in next way:

[rho, pvals] = corr(p);

corr in case produce m x m matrix contains correlation coefficient between each pair of columns n x m matrix stored in p.

hopefully 1 of these work!

matlab loops correlation

No comments:

Post a Comment