for loop output into matrix for pairwise comparisons
2 ビュー (過去 30 日間)
古いコメントを表示
I have 6 samples (mdio1-6), each with 100 observations that values range from 1 to 4 (integers). I would like to compare each of the samples for the number of observations that they are the same. So I have this code:
for n = 1:100
A = hap.mdio1
B = hap.mdio2
dist(n) = sum(abs(A(n)-B(n)))
end
metric = (100-(sum(dist12(:)==0)))/100
I have a couple of questions.
1. I do not understand how to add a loop to go through each of the comparisons possible (i.e. mdio01-mdio3, mdio1-mdio4, mdio1-mdio5, mdio1-mdio6 mdio02-mdio03, mdio02-mdio4 etc.).
2. I would like to put the value calculated in 'metric' into a matrix so that it is a 6x6 with the metric values for each of the comparisons (would be zeros along the diagonal because they all match).
Thanks!
0 件のコメント
回答 (3 件)
James Tursa
2015 年 4 月 3 日
編集済み: James Tursa
2015 年 4 月 3 日
As you are starting to see, having variables with "dynamic" names ending in 1, 2, 3, etc. can quickly cause programming headaches. You are forced into duplicating and hand editing multiple loops to get the processing you need. Or you resort to using eval, making your code klunky, hard to read and harder to debug. And if you have more that a handful of such variables it becomes too much of a burden. There are much better ways to program than this. E.g., see these links:
Stephen23
2015 年 4 月 3 日
編集済み: Stephen23
2015 年 4 月 3 日
>> str = sprintf('mdio%i',3)
str = 'mdio3'
hap.(str)
will access the data corresponding to the field name given by str. You should preallocate the output array, and then simply allocate the values using indexing. But it might be simpler to use non-scalar structure instead, as you will see in my example solution below.
>> X = nchoosek(1:6,2)
X =
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
The difference can also be calculated on the whole vectors by using vectorized code, rather than calculating in a loop for each of the elements in the vectors.
All together you might get something like this (a simplified example):
A(4).data = [0,2,3,4,5];
A(3).data = [1,2,3,4,5];
A(2).data = [1,0,3,4,0];
A(1).data = [0,2,3,4,5];
B = nchoosek(1:numel(A),2);
D = zeros(numel(A));
for k = 1:size(B,1)
x = B(k,1);
y = B(k,2);
D(x,y) = 1-mean(A(x).data==A(y).data);
end
where D is an upper-triangle matrix of the metric values:
>> D
D =
0 0.6 0.2 0
0 0 0.4 0.6
0 0 0 0.2
0 0 0 0
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!