Temp
Temp

Reputation: 33

Addition through linear indexing

I have a 256 x 256 matrix M, and have produced some linear indexes L.

Also I have a vector of weights, of numels same as L, to be added to the elements of M indexed by L. Problem is, with the expression

M(L) = M(L) + weights;

For duplicate values in L, only the last corresponding element in weights will be added.

Is there a simple way to resolve this/am I missing something?

Upvotes: 3

Views: 128

Answers (1)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

I think the way to go here is using accumarray:

% The 'data'
M = zeros(10,5); % Suppose this is your matrix
L = [46 47 47 46 48 49 48 48 48]'; % The linear index numbers
weights = [4 7 4 6 4 9 48 8 48]'; % The weights for these index numbers

% Make sure the indices are in ascending order
Y = SORTROWS([L weights]);

% Determining the weights to be added
idx = unique(Y(:,1));
weights_unique = accumarray(Y(:,1),Y(:,2));

% The addition
M(idx) = M(idx) + weights_unique(weights_unique>0);

Upvotes: 2

Related Questions