![](/img/trans.png)
[英]How can I find the maximum of sin(x) through matlab on an interval?
[英]How can I find the maximum gradient around a data point in Matlab?
我想找到在點P處漸變達到最大值的曲面上的x / y索引。
例如,讓我們看下面的曲面Z:
[X,Y] = meshgrid(-2:.2:2);
Z = X.*exp(-X.^2 - Y.^2);
Z(Z<0) = 0;
[DX,DY] = gradient(Z,.2,.2);
g = sqrt(DX.^2+DY.^2);
figure
contour(X,Y,Z)
hold on
quiver(X,Y,DX,DY)
hold off
假設峰的位置Z(21,28)是已知的。 現在,我正在尋找x / y索引,其中g(梯度)在此峰值附近達到最大值,這將是一條橢圓形的線。 如何做呢?
可以在單個點上達到最大梯度,可以使用max
函數輕松地計算出最大梯度(達到網格的精度),如下所示:
[~, i] = max(g(:));
[X(i), Y(i)]
我嘗試了以下方法,雖然效果不佳,但是可以實現該想法。
%% Scan g from the selected point P(y,x), and detect the border
% border : where g reaches its maximum somewhere close to P
P = [21,28]; % selected point: the peak, in this case
g_x = g(P(1,1),:);
r_b = right_border_x(g_x,P(1,2)); % see below
r0 = r_b - P(1,2); % initial guess for the radius
range = 0; % this is the range for function track_border_r (see below)
tracked_border = track_border_r(grad_temp,P(1,:),r0,360,range);
為了運行代碼,我編寫了兩個函數。 “ x_right_border”:
function x_right_border = right_border_x(gradient_vector,position_x)
% The function will search from position_x to the right hand side, i.e.
% values larger than position_x, till reach the border, defined via the
% maximum gradient.
g_xo = gradient_vector(position_x); % Gradient at the original position_x
g_xr = gradient_vector(position_x+1); % Gradient at its right neighbor
if g_xr < g_xo
x_right_border = position_x;
else
position_x = position_x+1;
x_right_border = right_border_x(gradient_vector,position_x);
end
end
,以及“ track_border_r”
function r_tracked = track_border_r(gradient_vector,center,r0,thetha_inc,range)
% gradient_vector : gradient of the surcface
% center(y,x) : selected center
% r0 : initial value of r for theta=0
% thetha_inc : number of increments of thetha, between 0 and 2*pi
% range: range for searching for max in the gradient vector around center
x_c = center(1,2);
y_c = center(1,1);
i = 1;
for theta = 0 : 2*pi/thetha_inc : 2*pi*(1-1/thetha_inc)
[x_i,y_i] = pol2cart(theta,r0);
x_r = x_i + x_c;
x_r = round(x_r-range:x_r+range);
y_r = round(y_i + y_c);
y_r = round(y_r-range:y_r+range);
g_temp = gradient_vector(y_r,x_r);
[~,ind] = max(g_temp(:));
[ind_row, ind_col] = ind2sub(size(g_temp),ind);
x_max = x_r(1) + ind_col - 1;
y_max = y_r(1) + ind_row - 1;
r0 = sqrt((x_max-x_c)^2 + (y_max-y_c)^2);
tracked(i,:) = [y_max,x_max];
i = i + 1;
end
r_tracked = unique(tracked,'rows');
end
通過更改函數“ track_border_r”中“ range”和“ thetha_inc”的值,可以在一定程度上控制其准確性; 但是,代碼無法完美運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.