Reputation: 431
This is my attempted code:
for i = 1:length(X) %X is a CSV matrix 50x4
Y = X(i, :) % fetching each row of X
dist = pdist2(Y, X2, 'euclidean') %X2 is another matrix 100x4
sumOfdist = sum(dist);
end;
meanResult = mean(sum)
sumOfdist will always be overwritten on each iteration and thus my meanResult stores the mean of only the last iteration. What would be the best way to store the sum of all the values through each iteration and using it outside the forloop to calculate the mean - without using global variables?
Upvotes: 0
Views: 228
Reputation: 19634
You can avoid using loop, and intead just do:
X=randn(6, 4);
X2=randn(10,4);
D = pdist2(X,X2,'euclidean');
sums=sum(D);
res=mean(sums)
In the code above, the i-th row in D
consists of list of distances of X(i,:)
from every row in X2
. Then in sums
we store the sum of each row in D
.
Upvotes: 2