Vectorization fail with sub2ind?
Afficher commentaires plus anciens
I have the for loop code
for m=1:numel(N,1)
y = N(m,1); % y matrix index
x = N(m,2); % x matrix index
dy = N(m,4); % codfficient
dx = N(m,3); % coefficient
wts(y,x) = wts(y,x)+dx.*dy;
end
I attempted to vectorize this as follows
ind = sub2ind(size(wts),N(:,2),N(:,1));
wts(ind) = wts(ind)+N(:,3).*N(:,4);
Unfortunately, for some reason the result is totally wrong.
This is a followup to a previous question : http://www.mathworks.com/matlabcentral/answers/119845-using-a-vector-of-indices-to-add-values-to-a-matrix
Someone later said that repeated values of "(x,y) / ind" will be erroneous. I don't know what that means, but there are many repeated values of the sub2ind index in my code (lots of addition).
How can this be fixed?
4 commentaires
per isakson
le 5 Mar 2014
Modifié(e) : per isakson
le 5 Mar 2014
>> numel( magic(6),1 )
ans =
1
did you intend
>> size( magic(6),1 )
ans =
6
What is the initial value of wts?
Anand
le 5 Mar 2014
What do you mean wrong result? The vectorized code looks right to me.
per isakson
le 5 Mar 2014
Modifié(e) : per isakson
le 5 Mar 2014
Why not show an executable example based on a for-loop?
Christopher
le 5 Mar 2014
Modifié(e) : Christopher
le 5 Mar 2014
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!