How to determine index for gradient?
조회 수: 5 (최근 30일)
이전 댓글 표시
Hello,
I'm trying to determine the index for a change in gradient along the radial direction from x=0 to x=1, which is expected to be negative. My code which runs but doesn't give correct result. Kindly have a look at the same and suggest me the possible correction(s) please.
data.variable.gradpressure = 10000 x 100 matrix
data.variable.x = 1 x 100 vector
Moreover the matchflag is also false when I try to match the columns which are both equal.
The code is as below:
% Determine the index for negative gradient from x=0 to x=1
clear grad_width;
global grad_width;
global data;
match_flags = false(size(data.variable.gradpressure,1),1); % Logical vector for matching rows
% Check if any row of pressure equals x
for i = 1:size(data.variable.x, 1)
if isequal(data.variable.gradpressure(:,i)', data.variable.x(:,i))
match_flags(i) = true;
end
end
%disp(match_flags)
threshold_fraction = 0.1;
% Preallocate result arrays
nTimes = length(data.variable.t);
grad_foot_idx = zeros(nTimes,1);
grad_head_idx = zeros(nTimes,1);
grad_width = zeros(nTimes,1);
for i = 1:nTimes
gradp = data.variable.gradpressure(i,:); % 1D vector at time i
% Avoid division by zero
valid = gradp(1:end-1) ~= 0;
% Compute gradient change (like second derivative)
change_gp = zeros(1, length(gradp)-1);
change_gp(valid) = diff(gradp)./gradp(1:end-1); % Central diff approx
% Find steepest drop (most negative change)
[max_grad1, max_grad1_idx] = min(abs(change_gp)); % Min of |second derivative|
grad_threshold = threshold_fraction * abs(max_grad1);
% Search left (foot)
left_idx = max_grad1_idx;
while left_idx > 1 && abs(change_gp(left_idx)) > grad_threshold
left_idx = left_idx - 1;
end
% Search right (head)
right_idx = max_grad1_idx;
while right_idx < length(change_gp) && abs(change_gp(right_idx)) > grad_threshold
right_idx = right_idx + 1;
end
% Store
grad_foot_idx(i) = left_idx;
grad_head_idx(i) = right_idx;
grad_width(i) = data.variable.x(right_idx) - data.variable.x(left_idx);
end
% Display last result (or modify to plot or analyze all)
disp(grad_width(end));
댓글 수: 0
채택된 답변
Alan Stevens
2025년 6월 24일
"Moreover the matchflag is also false when I try to match the columns which are both equal."
This suggests you are comparing floating point numbers which, though superficially look the same, are not actually identical because of the limited precision of stored floating point numbers. Rather than testing for exact equality, it's better to test for a small difference. For example, if x and y are floating point numbers then use something like:
matchflag = abs(x-y)<1e-15
댓글 수: 1
Steven Lord
2025년 6월 24일
x = 0:0.1:1;
0.3 == x % all false
ind = isapprox(0.3, x) % one true
y = x(ind) % "close enough" to 0.3
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!