我可以移动矩阵中的行吗 A
关于向量中的值 v
?
例如A
和 v
指定如下:
A =
1 0 0
1 0 0
1 0 0
v =
0 1 2
在这种情况下,我想从 A 得到这个矩阵:
A =
1 0 0
0 1 0
0 0 1
每个 i
A
中的第 - 行已被 i
转移-v
中的第一个值
我可以用原生函数做这个操作吗? 还是自己写?
我试过了 circshift
函数,但我不知道如何分别移动行。
最佳答案
函数 circshift
无法按您希望的那样工作,即使您使用向量表示偏移量,它也被解释为每个维度的偏移量。虽然可以遍历矩阵的行,但效率不高。
效率更高的是计算每一行的索引,这实际上非常简单:
## First, prepare all your input
octave> A = randi (9, 4, 6)
A =
8 3 2 7 4 5
4 4 7 3 9 1
1 6 3 9 2 3
7 4 1 9 5 5
octave> v = [0 2 0 1];
octave> sz = size (A);
## Compute how much shift per row, the column index (this will not work in Matlab)
octave> c_idx = mod ((0:(sz(2) -1)) .- v(:), sz(2)) +1
c_idx =
1 2 3 4 5 6
5 6 1 2 3 4
1 2 3 4 5 6
6 1 2 3 4 5
## Convert it to linear index
octave> idx = sub2ind (sz, repmat ((1:sz(1))(:), 1, sz(2)) , c_idx);
## All you need is to index
octave> A = A(idx)
A =
8 3 2 7 4 5
9 1 4 4 7 3
1 6 3 9 2 3
5 7 4 1 9 5
关于matlab - 相对于 Octave/MATLAB 中的向量值移动矩阵中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39056658/