I need to create matrices Dx
and Dy
that give the partial diferentials in the x and y directions respectivly when multipled by column stack representation of 2D area ( x
) so that Dx*x
will give me the partial derivetives in the x direction in vector form as well (the same dimentions as x
).
The derivitives are aproximated by:
f'(x,y) = 0.5*(f(x+1,y)-f(x-1,y)) for all x > 1 and x < n (the number of rows)
f'(1,y) = f(2,y)-f(1,y)
f'(n,y) = f(n,y)-f(n-1,y)
for Dx and similarly for Dy.
I tried creating the matrices using the fallowing code:
[X,Y] = meshgrid(1:n,1:m); % m,n - the dimentions of x
X = X(:)';
Y = Y(:)';
Dx = sparse(m*n,m*n);
Dy = sparse(m*n,m*n);
for x = 1:n
for y = 1:m
idx = y + (x-1)*m;
if (x == 1)
Dx(idx,:) = ((X == x+1) .* (Y == y)) - ((X == x) .* (Y == y));
elseif (x == n)
Dx(idx,:) = ((X == x) .* (Y == y)) - ((X == x-1) .* (Y == y));
else
Dx(idx,:) = 0.5*(((X == x+1) .* (Y == y)) - ((X == x-1) .* (Y == y)));
end
if (y == 1)
Dy(idx,:) = ((X == x) .* (Y == y+1)) - ((X == x) .* (Y == y));
elseif (y == m)
Dy(idx,:) = ((X == x) .* (Y == y)) - ((X == x) .* (Y == y-1));
else
Dy(idx,:) = 0.5*(((X == x) .* (Y == y+1)) - ((X == x) .* (Y == y-1)));
end
end
end
But this takes too much time, I feel that there should be a faster to create Dy
and Dx
?
About x
: for a 2D function represented by X
so that size(X)
is [nm]
, then x=X(:)
and size(x)
is [n*m 1]
Follow those steps:
convmtx2()
Function . This will get you what you wanted.
Horizontal Derivative: * Forward Finite Difference - $ [-1, 1] $. * Backward Finite Difference - $ [1, -1] $.
Vertical Derivative: * Forward Finite Difference - $ [-1; 1] $. * Backward Finite Difference - $ [1; -1] $.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.