I'm using matlab and I have this square matrix. I need to check whether it is block tridiagonal (with block of size NxN) or not. Is there a simple way to do that?
CodePudding user response:
Assuming a [r x r] matrix A and blocks of size [N x N] construct a block tridiagonal matrix of 1s and 0s k and compare indexes of nonzero elements of both matrices A and k:
r = size(A, 1);
Bin = ones(r/N, 3);
S = spdiags(Bin, -1:1, r/N, r/N);
k = kron(S, ones(N));
f = find(k);
fA = find(A);
is_A_block_tridiagonal = all(ismember(fA, f));
CodePudding user response:
You can use the diag function for extracting diagonals and placing them in the new matrix (M_3_diags_only). Do this 3 times for every diagonal (first, underneath (-1), above ( 1)).
If you add these diagonals, it should produce the same matrix as the original one (M) only in case of tridiagonal matrix.
N = 6; %size definition
M = randi([0 9],[N N]); %random numbers
%creates matrix, where only 3 diagonals (main,-1st, 1st) are copied
% rest is 0
M_3_diags_only = diag(diag(M)) diag(diag(M,-1),-1) diag(diag(M, 1), 1);
isTridiagonal = issame(M,M_3_diags_only)%check if the matricis are the same
