gpt4 book ai didi

matlab - 通过线性索引进行加法

转载 作者:行者123 更新时间:2023-12-02 06:23:55 30 4
gpt4 key购买 nike

我有一个 256 x 256 矩阵 M,并生成了一些线性索引 L。

我还有一个权重向量,其数值与 L 相同,将添加到由 L 索引的 M 元素中。问题是,用表达式

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

对于L中的重复值,仅添加权重中最后一个对应的元素。

有没有一个简单的方法来解决这个问题/我错过了什么吗?

最佳答案

我认为这里的方法是使用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);

关于matlab - 通过线性索引进行加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13599688/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com