matlab:不带 sub2ind 的一个索引的寻址

发布于 2024-11-04 21:40:10 字数 755 浏览 4 评论 0原文

这与 另一个问题密切相关,但该问题想要出于性能考虑,避免使用 sub2ind。我更担心使用sub2ind的“不优雅”。

假设我想创建另一个 MxN 矩阵,除了每列中的一个条目(我想从向量中的相应条目分配)之外,该矩阵全为零,并且每列中行的选择基于另一个向量。例如:

z = zeros(10,4);
rchoice = [3 1 8 7];
newvals = [123 456 789 10];
% ??? I would like to set z(3,1)=123, z(1,2)=456, z(8,3)=789, z(7,4)=10

我可以使用 sub2ind 来完成此操作(我在 答案中使用它一个密切相关的问题):

z(sub2ind(size(z),rchoice,1:4)) = newvals

但是还有其他选择吗?似乎逻辑寻址可以以某种方式使用,但我很困惑,因为为了将逻辑矩阵的元素设置为 1,您要处理与实际想要寻址的矩阵中相同的元素位置。

This is very closely related to this other question, but that question wanted to avoid sub2ind because of performance concerns. I am more concerned about the "unelegance" of using sub2ind.

Let's suppose I want to create another MxN matrix which is all zeros except for one entry in each column that I want to assign from the corresponding entry in a vector, and choice of row in each column is based on another vector. For example:

z = zeros(10,4);
rchoice = [3 1 8 7];
newvals = [123 456 789 10];
% ??? I would like to set z(3,1)=123, z(1,2)=456, z(8,3)=789, z(7,4)=10

I can use sub2ind to accomplish this (which I used in an answer to a closely related question):

z(sub2ind(size(z),rchoice,1:4)) = newvals

but is there another alternative? Seems like logical addressing could be used in some way but I'm stumped, because in order to set the elements of a logical matrix to 1, you're dealing with the same element positions as in the matrix you actually want to address.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

卖梦商人 2024-11-11 21:40:10

有一种更简单的方法可以做到这一点。

nCols=size(z,2);
z(rchoice,1:nCols)=diag(newvals);

There's a much simpler way of doing it.

nCols=size(z,2);
z(rchoice,1:nCols)=diag(newvals);
怕倦 2024-11-11 21:40:10

您只需将前几列的行数添加到rchoice即可直接获取线性索引。

nRows = size(z,1); %# in case you don't know this already
nCols2write = length(newvals);
z(rchoice+[0:nRows:(nRows*(nCols2write-1)]) = newvals;

You can just add the number of rows in previous columns to rchoice to get the linear index directly.

nRows = size(z,1); %# in case you don't know this already
nCols2write = length(newvals);
z(rchoice+[0:nRows:(nRows*(nCols2write-1)]) = newvals;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文