Effacer les filtres
Effacer les filtres

How to vectorize this simple for-loop

1 vue (au cours des 30 derniers jours)
Felix Lauwaert
Felix Lauwaert le 19 Août 2015
Commenté : Felix Lauwaert le 19 Août 2015
Hello,
I'm trying to vectorize something like this:
z=zeros(3); x=[1 2 3]; y=x;
for i=1:length(x) %or y, doesn't matter
z( x(i),y(i) )=z( x(i),y(i) ) + 1;
end
So
z= [1 0 0 ; 0 1 0 ; 0 0 1]
What I really want is to do it for any x and y vectors in a 1000by1000 zero matrix.
I tried to do:
z(x,y)=z(x,y)+1;
But I get all values of z =1. I also tried:
z(x.,y.)=z(x.,y.)+1;
But an error message appears.
Thanks for your help.

Réponse acceptée

Matt J
Matt J le 19 Août 2015
Modifié(e) : Matt J le 19 Août 2015
idx=sub2ind(size(z),x,y);
z(idx)=z(idx)+1;
  2 commentaires
Felix Lauwaert
Felix Lauwaert le 19 Août 2015
Error using sub2ind (line 52) Out of range subscript.
Felix Lauwaert
Felix Lauwaert le 19 Août 2015
idx=sub2ind([length(x),length(x)],x,y); z(idx)=z(idx)+1;
Is working. Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by