Speeding up 2D Finite Difference Matrix

I have two matrices B and D, where B is a matrix and D is a matrix defined as follows:
with ,
where is the identity matrix and denotes the Kronecker product of matrices P and Q. I am currently computing B as a sparse matrix as follows:
o = ones(n,1);
z = zeros(n,1);
D = spdiags([-o o z],-1:1,n,n);
D(1,1) = 0;
I = speye(n);
B1 = kron(I, D);
B2 = kron(D, I);
B = [B1;B2];
I know that can be quickly computed using
[0; diff(x)]
I need to find a quick way of computing and in a similar manor. Currently my code is spending a signifigant amount of its time to compute and so I was wondering if anyone had some incite into computing this efficently.

 Réponse acceptée

Chris J
Chris J le 9 Mar 2020
I solved it here is my solution:
U = reshape(x, [n,n]);
u1 = [zeros([1,n]); diff(U, 1, 1)];
u2 = [zeros(n, 1), diff(U, 1, 2)];
y = [u1(:); u2(:)];
To solved for we solve the equavalent formulation :
x1vec = x(1:end/2);
x2vec = x(end/2+1:end);
x1mat = reshape(x1vec, [n,n]);
x2mat = reshape(x2vec, [n,n]);
p1 = -diff(x1mat, 1, 1);
p1 = [-x1mat(2, :); p1(2:end,:); x1mat(end,:)];
p1 = p1(:);
p2 = -diff(x2mat, 1, 2);
p2 = [-x2mat(:,2), p2(:, 2:end), x2mat(:,end)];
p2 = p2(:);
y = p1+p2;

Plus de réponses (0)

Catégories

En savoir plus sur Descriptive Statistics dans Centre d'aide et File Exchange

Produits

Version

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by