matlab:不带 sub2ind 的一个索引的寻址
这与 另一个问题密切相关,但该问题想要出于性能考虑,避免使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一种更更简单的方法可以做到这一点。
There's a much simpler way of doing it.
您只需将前几列的行数添加到
rchoice
即可直接获取线性索引。You can just add the number of rows in previous columns to
rchoice
to get the linear index directly.