简体   繁体   中英

Creating a differential matrix in Matlab

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:

  1. Represent the operation using a Filter. Derivative Filters are easy the way you defined the above.
  2. Create the Convolution Matrix using MATLAB's convmtx2() Function .

This will get you what you wanted.

Derivative Filters in Image Processing

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM