Hi,I want to find the position not value of an element of a vector that meet equal a number, I have this vector z=[0:-0.01:-16] and want to find the position when z=-2 .

 채택된 답변

Cam Salzberger
Cam Salzberger 2017년 10월 18일

6 개 추천

Hello Farhan,
You can use find to get the index when an expression is true, and "==" to get that logical array. Something like this should work:
idx = find(z == -2);
Note, however, that this will only do an absolute comparison. If you wanted to find with some kind of tolerance, you could do:
idx = find(abs(z+2) < 0.001);
Also note that if you are then going to use this index for indexing into the array, it's usually more efficient to just use the logical array to index:
z(z == -2) = NaN; % Or something
Hope this helps!
-Cam

댓글 수: 4

F.O
F.O 2017년 10월 18일
Thanks man but I dont get a correct answer and the correct answer shou1d be 21 but what by using your first coding is 201.
Stephen23
Stephen23 2017년 10월 18일
편집: Stephen23 2017년 10월 18일
@Farhan Omar: here are the 201st and 21st elements:
>> z(21)
ans = -0.20000
>> z(201)
ans = -2
Note that Star Strider's answer using ismembertol will be much more robust than this answer.
F.O
F.O 2017년 10월 18일
I am sorry I had a mistake in the step which is 0.1 not 0.01 thanks for the answer and it make sense
Star Strider
Star Strider 2017년 10월 18일
@Stephen — Thank you!

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

추가 답변 (3개)

Star Strider
Star Strider 2017년 10월 18일
편집: Star Strider 2017년 10월 18일

7 개 추천

The ismember (or perhaps preferably ismembertol) function is your friend here.
EDIT The ‘-2’ index will be 21 if the step in ‘z’ is ‘-0.1’ rather than ‘-0.01’:
z=[0:-0.1:-16];
[~,idx] = ismembertol(-2, z, 1E-8)
idx =
21

댓글 수: 2

F.O
F.O 2017년 10월 18일
Thanks it works but it is difficult to understand how it works
Star Strider
Star Strider 2017년 10월 18일
The ismembertol function checks to see whether the first argument (here -2) is a member of the set in the second argument (here ‘z’), and returns the index/indices in the second argument that match. Since floating-point calculations (including those involved in the colon operator calculations) can produce values that are not exactly -2 (in this instance), the third ‘tolerance’ argument gives a range of values around -2 that would meet the criterion. The find and ismember functions match the condition exactly, while ismembertol matches within a tolerance.
See: Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero? (link) for a full explanation of the reason ismembertol may be the preferred function, if there is a reason to suspect that no element of ‘z’ is exactly equal to -2.

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

KL
KL 2017년 10월 18일
편집: KL 2017년 10월 18일

0 개 추천

[row,col,v] = find(z==-2)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

태그

질문:

F.O
2017년 10월 18일

댓글:

2017년 10월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by