如何在MATLAB中构建这些梯度和发散矩阵?

时间:2017-05-28 12:35:29

标签: matlab matrix sparse-matrix

如果我有h和w,我如何构造矩阵G和D?

请注意G中有0行,而D中有0列......

gradient matrix G

divergent matrix D

2 个答案:

答案 0 :(得分:1)

即使我对这个问题的解决方案已经很晚了,但是这里是任何想要实现它的人:

b

该解决方案的优势在于可以使用matlabs稀疏对角矩阵,该矩阵使您可以为大型图像创建梯度矩阵,并更快地进行计算。

要获得差异,请简单地使用:

function g = gradientMat(w,h)
    one = [-ones(w*h,1) ones(w*h,1)];
    d = [0 1];
    dx = spdiags(one,d,w*h,w*h);
    dx(1:h:end,:) = zeros(w,w*h);
    d = [0 h];
    dy = spdiags(one,d,w*h,w*h);
    dy(h*(w-1)+1:end,:) = zeros(h,w*h);
    g = [dx;dy];
end

答案 1 :(得分:0)

这就是我现在的做法,但必须有更优雅的方式,对吧?!

%% construct G

% upper half
firstDiagG = ones(h, 1);
firstDiagG(h) = 0;
firstDiagG = -firstDiagG;
firstDiagG = repmat(firstDiagG,w,1);

% first = diag(firstDiagG);
firstG = spdiags(firstDiagG,0,n,n);


secondDiagG = ones(h, 1);
secondDiagG(h) = 0;
secondDiagG = repmat(secondDiagG,w,1);

% second = diag(secondDiagG);
secondG = spdiags(secondDiagG,0,n,n);
secondG = [zeros(size(secondG,1),1) secondG];
secondG = secondG(:,1:end-1);

upperHalf = firstG + secondG;

% lower half
thirdDiagG = ones(n-h, 1);
thirdDiagG = [thirdDiagG; zeros(h, 1)];
thirdDiagG = -thirdDiagG;

% thirdG = diag(thirdDiagG);
thirdG = spdiags(thirdDiagG,0,n,n);

fourthDiagG = [ones(n-2*h, 1); zeros(n-2*h, 1)];

% fourthG = diag(fourthDiagG);
fourthG = spdiags(fourthDiagG,0,n,n);
fourthG = [zeros(size(fourthG,1), h) fourthG];
fourthG = fourthG(:,1:end-h);
% fourthG = [fourthG zeros(size(fourthG,1),h)];
% fourthG = [fourthG; zeros(size(fourthG,1), size(fourthG,2))];

lowerHalf = thirdG + fourthG;

G = [upperHalf; lowerHalf];

%% construct D

% left half
firstD = firstG;            % is the same as in G

secondDiagD = secondDiagG;  % is the same as in G

% secondD = diag(secondDiagD);
secondD = spdiags(secondDiagD,0,n,n);
secondD = [zeros(1, size(secondD,1)); secondD];
secondD = secondD(1:end-1,:);

leftHalf = firstD + secondD;

% right half
thrirdDiagD = flip(thirdDiagG);

% thirdD = diag(thrirdDiagD);
thirdD = spdiags(thrirdDiagD,0,n,n);

fourthDiagD = ones(n, 1);

% fourthD = diag(fourthDiagD);
fourthD = spdiags(fourthDiagD,0,n,n);
fourthD = [zeros(h, size(fourthD,1)); fourthD];
fourthD = fourthD(1:end-h,:);

rightHalf = thirdD + fourthD;

D = [leftHalf rightHalf];