Position of an element in a vector
Ältere Kommentare anzeigen
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 .
Akzeptierte Antwort
Weitere Antworten (3)
Star Strider
am 18 Okt. 2017
Bearbeitet: Star Strider
am 18 Okt. 2017
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 Kommentare
F.O
am 18 Okt. 2017
Star Strider
am 18 Okt. 2017
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.
[row,col,v] = find(z==-2)
Jan
am 18 Okt. 2017
Remember the old FAQ:
Why does
any((0:0.1:1) == 0.3)
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!