Can I shift rows in matrix A
with respect to values in vector v
?
For instance A
and v
specified as follows:
A =
1 0 0
1 0 0
1 0 0
v =
0 1 2
In this case I want to get this matrix from A:
A =
1 0 0
0 1 0
0 0 1
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?
I've tried circshift
function, but I couldn't figure out how to shift rows separately.
If performance is an issue, you can replace
repmat
with an equivalentbsxfun
call which is more efficient (I use repmat here for simplicity to demonstrate the approach).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:
Shift vector with
circshift
in loop, iterating row index.With focus on performance, here's one approach using
bsxfun/broadcasting
-Sample run -
Equivalent Octave version to use
automatic broadcasting
would look something like this -