필터 지우기
필터 지우기

Finding a noninteger value from an array

조회 수: 10 (최근 30일)
SAZZAD HOSSAIN
SAZZAD HOSSAIN 2012년 12월 20일
댓글: Matthew Murphy 2016년 7월 6일
I have an array which looks like:
x = linspace(0,1,101);
To find the index of the maximum point from an array, I can write:
[val,ind] = max(x);
However, I need the index of a particular point, let's say 0.70. How should i write the commands to find this?
My second question is that I have a specific value y = 0.703. I need to do my calculation using the array x, but I have to start from the value in x that is closest to y. Which means I am looking for the index of the point 0.70 in x, but i need to express it in terms of y in my code. How can I do that?

채택된 답변

Matt J
Matt J 2012년 12월 20일
Both questions have the same answer
[~,loc]=min(abs(x-y))

추가 답변 (2개)

Kye Taylor
Kye Taylor 2012년 12월 20일
편집: Kye Taylor 2012년 12월 20일
To do (1) and (2) try
y = 0.7; % or y = 0.73;
[~,idx] = min(abs(x-y));
% idx contains the index of the value in x closest to y

Matthew Murphy
Matthew Murphy 2016년 7월 6일
Given the array x, you could also use the find command.
find(x == .7) --> ans = 71
For the second part, you could try a slightly different way with the same command.
Given some plus/minus window of .01, you could do this:
find(x < .703 + .01 & x > .703 - .01 ) --> ans = 71 72
Now, there are multiple values, so you could use a while loop with smaller and smaller margins until one value is found (with a catch to widen the margin if no values are found).
[I know this is an old post, but I still wanted to follow up with an approach that worked for me.]
  댓글 수: 2
Matt J
Matt J 2016년 7월 6일
편집: Matt J 2016년 7월 6일
Using find() without floating point tolerances can be hit or miss, for example,
>> x=0:0.3:1
x =
0 0.3000 0.6000 0.9000
>> find(x==(1-.7))
ans =
Empty matrix: 1-by-0
That is why I recommended the use of min() for both scenarios raised by the OP,
>> [~,loc]=min(abs(x-(1-.7)))
loc =
2
Matthew Murphy
Matthew Murphy 2016년 7월 6일
I think my version would work if you had the explicit value (eg .3) used in find.
x=0:0.3:1
x =
0 0.3000 0.6000 0.9000
find(x == .3)
ans =
2
You are definitely right with the tolerance issue, no problem there. In my application, I had points to search for, so I had exact values.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by