Another way instead of for loop

2 次查看(过去 30 天)
muhammad ismat
muhammad ismat 2015-6-18
编辑: Guillaume 2015-6-18
I have this code
for i = 1:34
for j = 1:i % <-- Note the 1:i instead of 1:n
s(i,j) = abs(z(i,ind(j))-z(j,ind(i)))/(z(i,ind(j))+z(j,ind(i)));
s(j,i) = s(i,j)
end
end
firstly, i make a cluster to specific matrix(840000 x 840000) then i want to calculate previous code (with another way instead of for loop) to each point in the matrix
where 'ind' is cluster no that a point belong to, z is the distance from point to a cluster

回答(1 个)

Guillaume
Guillaume 2015-6-18
编辑:Guillaume 2015-6-18
The following should work. Basically, use ndgrid (or meshgrid) and sub2ind to compute all your indices at once:
[direct, indirect] = ndgrid(1:34, ind(1:34));
index1 = sub2ind(size(z), direct, indirect));
index2 = sub2ind(size(z), indirect, direct));
s = abs(z(index1) - z(index2)) ./ (z(index1) + z(index2));
I'm calculating the whole matrix at once instead of just the lower triangle as that will be faster anyway than flipping and copying the lower triangle.

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by