Clear Filters
Clear Filters

How to find when the value is 0 in an array?

118 views (last 30 days)
Im plotting a graph of X against Y and i want to know the value of X when Y = 0. I have tried to use the find command and doing find(Y==0) but because in the array there is no exact zero number (goes to 0.00024 then to negative) it wont return anything.
Y = (U_y .* time) - (0.5 .* g .* (time).^2) + handles.Height;
Index = find(Y==0)
X_point = X(Index)

Answers (2)

Rik
Rik on 5 Dec 2018
This answer contains code to find the zero crossing in a vector
https://www.mathworks.com/matlabcentral/answers/267222-easy-way-of-finding-zero-crossing-of-a-function#answer_209072

Walter Roberson
Walter Roberson on 5 Dec 2018
[~, Index] = min(abs(Y));
The zero crossing will be between the point at Index and the next point over in one of the two directions.
You could also use
mask = Y > 0;
% goes from positive to negative ?
Index = find(Y(1:end-1) & ~Y(2:end));
if isempty(Index);
% goes from negative to positive ?
Index = find(~Y(1:end-1) & Y(2:end));
end
if isempty(Index)
%no zero crossing
end
  2 Comments
Greg Simmons
Greg Simmons on 8 Aug 2022
very clever!... this second script helped me a lot. Thanks Walter.
Walter Roberson
Walter Roberson on 8 Aug 2022
The script should probably be
mask = Y > 0;
% goes from positive to negative ?
Index = find(mask(1:end-1) & ~mask(2:end));
if isempty(Index);
% goes from negative to positive ?
Index = find(~mask(1:end-1) & mask(2:end));
end
if isempty(Index)
%no zero crossing
end

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!