I am looking for a matrix operation of the form: B = M*A*N
where A
is some general square matrix and M
and N
are the matrices I want to find.
Such that the columns of B
are the diagonals of A
. The first column the main diagonal, the second the diagonal shifted by 1 from the main and so on.
e.g. In MATLAB syntax:
A = [1, 2, 3
4, 5, 6
7, 8, 9]
and
B = [1, 2, 3
5, 6, 4
9, 7, 8]
Edit: It seems a pure linear algebra solution doesn't exist. So I'll be more precise about what I was trying to do:
For some vector v
of size 1 x m
. Then define C = repmat(v,m,1)
. My matrix is A = C-C.';
.
Therefore, A
is essentially all differences of values in v
but I'm only interested in the difference up to some distance between values.
Those are the diagonals of A
; but m
is so large that the construction of such m x m
matrices causes out-of-memory issues.
I'm looking for a way to extract those diagonals in a way that is as efficient as possible (in MATLAB).
Thanks!
If you're not actually looking for a linear algebra solution, then I would argue that constructing three additional matrices the same size as
A
using two matrix multiplications is very inefficient in both time and space complexity. I'm not sure it's even possible to find a matrix solution, given my limited knowledge of linear algebra, but even if it is it's sure to be messy.Since you say you only need the values along some diagonals, I'd construct only those diagonals using
diag
:Diagonal
0
is the main diagonal, diagonalm-1
(for anmxm
matrix) is the last. So if you wanted all ofB
you could easily loop:From the comments:
Let's say
If you construct the entire matrix,
The main diagonal is zeros, so that's not very interesting. The next diagonal, which I'll call
k = 1
isYou can construct this diagonal without constructing
A
or evenB
by shifting the elements ofv
:The main diagonal is given by
k = 0
, the last diagonal byk = m-1
.