Azzera filtri
Azzera filtri

Another way instead of for loop

2 visualizzazioni (ultimi 30 giorni)
muhammad ismat
muhammad ismat il 18 Giu 2015
Modificato: Guillaume il 18 Giu 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

Risposte (1)

Guillaume
Guillaume il 18 Giu 2015
Modificato: Guillaume il 18 Giu 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.

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by