6 views (last 30 days)

How i will find mathematically what is the position of the element correspounding z=-2 it is 21 but I cant find it mathematically

p=[4.4 5.5 6.6 8];

h=[2 5 3 6];

x=[0:0.4:40];

z=[0:-0.1:-16]

vel=zeros(numel(z),numel(x));

vel(1:21,:)=4.4;

vel(22:71,:)=5.5;

vel(72:101,:)=6.6;

vel(102:161,:)=8;

Stephen Cobeldick
on 11 Dec 2017

Edited: Stephen Cobeldick
on 11 Dec 2017

You need to compare the difference against a (carefully selected) tolerance:

>> z = 0:-0.1:-16; % do not use square brackets!

>> tol = 0.00001;

>> val = -4.4;

>> idx = find(abs(z-val)<=tol)

idx = 45

>>

Read more here:

Sign in to comment.

James Tursa
on 11 Dec 2017

Edited: James Tursa
on 11 Dec 2017

You need to be careful how you search for this element. Because of the way the colon operator works with floating point fractions, you cannot guarantee that values you think might obviously be in the vector are actually there exactly. E.g.,

>> z=[0:-0.1:-16];

>> find(z==-4.4)

ans =

45

>> num2strexact(-4.4)

ans =

-4.4000000000000003552713678800500929355621337890625

>> num2strexact(z(45))

ans =

-4.4000000000000003552713678800500929355621337890625

>> find(z==-4.1)

ans =

Empty matrix: 1-by-0

>> num2strexact(-4.1)

ans =

-4.0999999999999996447286321199499070644378662109375

>> num2strexact(z(42))

ans =

-4.10000000000000053290705182007513940334320068359375

So, for the -4.4 value the colon operator happen to pick the same "closest" IEEE double value that you get when you type the value at the command line. But this didn't happen for the -4.1 value. So to do these types of operations in your code, you need to account for this effect and either use tolerances or use some type of integer range that you know can be searched exactly.

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/372337-find-the-position-of-en-element-if-you-have-the-increment#comment_515054

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/372337-find-the-position-of-en-element-if-you-have-the-increment#comment_515054

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/372337-find-the-position-of-en-element-if-you-have-the-increment#comment_515066

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/372337-find-the-position-of-en-element-if-you-have-the-increment#comment_515066

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/372337-find-the-position-of-en-element-if-you-have-the-increment#comment_515076

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/372337-find-the-position-of-en-element-if-you-have-the-increment#comment_515076

Sign in to comment.