Matlab:一个没有sub2ind的索引的寻址 [英] matlab: addressing of one index without sub2ind

查看:105
本文介绍了Matlab:一个没有sub2ind的索引的寻址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与其他问题密切相关,但是由于性能方面的考虑,该问题希望避免使用sub2ind.我更担心使用sub2ind的不确定性".

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.

让我们假设我要创建另一个MxN矩阵,除了要从向量中的相应条目分配的每列中的一个条目之外,其余均为零,并且每列中的行的选择基于另一个向量.例如:

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

我可以使用sub2ind完成此操作(我在中使用了此答案):

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

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

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.

推荐答案

有一种很多更简单的方法.

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

这篇关于Matlab:一个没有sub2ind的索引的寻址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆