相对于Octave/MATLAB中的向量值移动矩阵中的行 [英] Shift rows in matrix with respect to vector values in Octave/MATLAB

查看:77
本文介绍了相对于Octave/MATLAB中的向量值移动矩阵中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以相对于向量v中的值移动矩阵A中的行吗?

Can I shift rows in matrix A with respect to values in vector v?

对于实例Av,其指定如下:

For instance A and v specified as follows:

A =
    1   0   0
    1   0   0
    1   0   0

v =
    0   1   2

在这种情况下,我想从A获取此矩阵:

In this case I want to get this matrix from A:

A = 
    1   0   0
    0   1   0
    0   0   1

A中的每个i行都已移位v中的i位值

Every i-th row in A has been shifted by i-th value in v

我可以使用本机函数执行此操作吗? 还是我应该自己写?

Can I do this operation with native functions? Or should I write it by myself?

我已经尝试过circshift函数,但是我不知道如何分别移动行.

I've tried circshift function, but I couldn't figure out how to shift rows separately.

推荐答案

函数circshift不能按您期望的方式工作,即使您将向量用作偏移量,也将其解释为每个维度.虽然可以循环遍历矩阵的行,但这并不是很有效.

The function circshift does not work as you want and even if you use a vector for the amount of shift, that is interpreted as the amount of shift for each dimension. While it is possible to loop over the rows of your matrix, that will not be very efficient.

更高效的是,如果您为每行计算索引,这实际上非常简单:

More efficient is if you compute the indexing for each row which is actually quite simple:

## 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

这篇关于相对于Octave/MATLAB中的向量值移动矩阵中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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