Borrar filtros
Borrar filtros

Another way instead of for loop

2 visualizaciones (últimos 30 días)
muhammad ismat
muhammad ismat el 18 de Jun. de 2015
Editada: Guillaume el 18 de Jun. de 2015
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

Respuestas (1)

Guillaume
Guillaume el 18 de Jun. de 2015
Editada: Guillaume el 18 de Jun. de 2015
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.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by