Vectorization fail with sub2ind?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Christopher
am 4 Mär. 2014
Kommentiert: Christopher
am 5 Mär. 2014
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 Kommentare
per isakson
am 5 Mär. 2014
Bearbeitet: per isakson
am 5 Mär. 2014
Why not show an executable example based on a for-loop?
Akzeptierte Antwort
Roger Stafford
am 5 Mär. 2014
Bearbeitet: Roger Stafford
am 5 Mär. 2014
Here's a simple example to show you how repeated values of 'ind' will produce different results from your for-loop:
wts = zeros(3,1);
ind = [2;2;2];
wts(ind) = wts(ind) + [3;7;19];
wts
ans =
0
19
0
In your vectorization you would have been expecting [0;29;0] as in a for-loop, but instead only the last addition is performed, the other two results having been overwritten.
To do what you want, use matlab's 'accumarray' function:
wts = wts + accumarray([N(:,1),N(:,2)],N(:,3).*N(:,4),size(wts));
It will perform all the additions, even with repetitions.
(Note: You appear to have N(:,2) and N(:,1) in reversed order in your call to 'sub2ind' which would produce further errors.)
1 Kommentar
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!