这是我要在MATLAB中重现的Python代码。
>>> M = np.zeros((5,5))
>>> indices = np.arange(5)
>>> M[indices[:-1], indices[:-1]+1] = 1
>>> print(M)
[[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0.]]
这是我在MATLAB中编写代码时发生的事情。
>> M = zeros(5);
>> indices = 1:5;
>> M(indices(1:end-1), indices(1:end-1)+1) = 1
>>
M =
0 1 1 1 1
0 1 1 1 1
0 1 1 1 1
0 1 1 1 1
0 0 0 0 0
如何在MATLAB中实现相同的索引编制效果?
答案 0 :(得分:3)
MATLAB 2D索引提取一个矩形子矩阵,并根据提供的索引向量对其行和列进行重新排序。但是,如果您有行和列的列表,并且要提取相应的元素,则应将2D索引转换为线性索引,可以使用sub2ind:
M = zeros(5);
indices = 1:5;
idx = sub2ind([5,5],indices(1:end-1), indices(1:end-1)+1);
M(idx) = 1
或者,您可以直接使用线性索引:
M = zeros(5);
M(5+1:5+1:end) = 1
线性索引如何工作? 在MATLAB中,数据以列主格式存储:
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
使用范围6:6:end
时,这意味着您希望以步长6开始以表单元素6的形式提取元素,因此需要元素[6 12 18 24]
。该索引方案可以扩展到ND数组和非平方矩阵。