Filter löschen
Filter löschen

Another way instead of for loop

2 Ansichten (letzte 30 Tage)
muhammad ismat
muhammad ismat am 18 Jun. 2015
Bearbeitet: Guillaume am 18 Jun. 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

Antworten (1)

Guillaume
Guillaume am 18 Jun. 2015
Bearbeitet: Guillaume am 18 Jun. 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.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by