how to get the x value for a given y value?

조회 수: 54 (최근 30일)
ahmed salah
ahmed salah 2019년 5월 22일
댓글: Jan 2021년 2월 2일
I plot x-y graph (Gaussian function) and want to get the x-axis value (will be two points in this case) at a certain y-axis value (half of the maximum)
I tried this but it didn't work:
clc;
clear all;
Fs = 150; % Sampling frequency
t = -0.5:1/Fs:0.5; % Time vector of 1 second
x = 1/(sqrt(2*pi*0.01))*(exp(-t.^2/(2*0.01)));
figure;
plot(t,x);
xi = 0.5*max(x) ;
z=find(x==xi);
ti = x(z) ;
hold on
plot(ti,xi,'*r')

채택된 답변

Geoff Hayes
Geoff Hayes 2019년 5월 22일
ahmed - your code assumes that there is an x value that is identical to xi
z=find(x==xi);
This need not be true. And comparing doubles in this manner is not generally a good idea (due to precision, see Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero?). Usually a tolerance of some kind should be used (i.e. abs(x - y) < eps). In your case, a tolerance might not work as well because you will not know what that tolerance should be. You could try different values...the following seems to work for this dataset
z=find(abs(x-xi)< 0.10);
ti = t(z) ;
hold on
plot(ti,xi,'*r')
(Note how ti is obtained from the t array instead of x.)

추가 답변 (1개)

Jan
Jan 2019년 5월 22일
You cannot expect that any of the points at t = -0.5:1/Fs:0.5 is exactly 0.5*max(x). Remember that you evaluate x at some time steps only and rounding errors have to be considered also.
There is an analytical solution also, but you can use fzero to find the searched points. But you have to find the maximum value of the curve at first. Setting the derivative to 0 will help you.
  댓글 수: 2
Parmonangan Manalu
Parmonangan Manalu 2021년 2월 2일
편집: Parmonangan Manalu 2021년 2월 2일
clear;
a = 6.8;
b = 10;
weight = 767;
for i = 1:22
if i>= a && i <= b
gra = (1.4);
else
gra = 0;
end
GM(i) = gra.*weight;
format long g
end
dis = 1:22;
plot(dis,GM)
grid on
ax = gca;
ax.XAxis.TickLabelFormat = '%,.1f';
Dear Jan,
can you please help with that coding, the y value is not exatcly as the x value when i plot the graph. I think the correct graph shall be the red line
thanks in advance
Jan
Jan 2021년 2월 2일
Please open a new thread for a new question. Posting new question is the section for comments to answers of another question is too confusing.
The code produces the diagram exactly as expected. Note that the diagram of x=[1,2,3], y = [0,1,0] is a triangle also. If you post this as new question, we will write some answers about how you can achieve, what you want.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by