MATLAB Answers


How can Fix the "find" with for loop

Asked by ahmed youssef on 13 Apr 2017
Latest activity Commented on by Roger Stafford on 13 Apr 2017
Hi, I am Struggling to get the hidden error. I just need to put the specific markers at specific points on the chirp graph. The problem is that it gives me the error " 1×0 empty double row vector" at specific line AND when I wrote this line manually to get the indices, I got the answer without error. is that bug or am I missing something? please help. I attach my code you can run and you will get the error at point (301) i.e (x= .3). if you write Y(X==.3), you'll get the answer although it gave you error in the code.
fs=1e3; X = 0:1/fs:2-(1/fs); fo = 1; f1 = 5; Y = chirp(X,fo,X(end),f1,'logarithmic'); points=zeros(2,20); xe =0:.1:X(end); for i=1:length(xe) i index = find(X==xe(i)) X_point=X(index); Y_point= Y(X==xe(i)); points(1,i)=X_point; points(2,i)=Y_point; plot(X,Y,X_point,Y_point,'*') labelstr = sprintf('%d',i); text(X(index)+.05,Y_point, labelstr); hold on end


Sign in to comment.

1 Answer

Answer by Roger Stafford on 13 Apr 2017

In your code you are assuming that the ‘find’ operation will always find an index from X that will match one in xe. The trouble is that the decimal fraction values in these vectors cannot be exactly represented since your computer uses binary numbers. Presumably the two representations of .3 in the two vectors are slightly different, yielding an empty status for 'index'. To correct this you should allow a tiny tolerance for such differences rather than requiring exact equality.


Added: The fact that Y(X==.3) gives an answer is not in contradiction with the above. Here are the actual computer values as expressed in format hex:
xe(4) -> 3fd3333333333334
X(301) -> 3fd3333333333333
.3 -> 3fd3333333333333
As you can see, X==.3 has an exact match, but X==xe(4) doesn’t. The latter is off in the least significant bit. And of course none of these is exactly 3/10 since that cannot be expressed exactly in binary.
thank you for your answer, can you give me any suggestion gives me that tolerance.
index = find(abs(X-xe(i))<tol);
in place of
index = find(X==xe(i))
The ‘tol’ value should be smaller than the smallest difference that you want to elicit a false value and larger than the largest you tolerate for a true value. In your case these appear to be about .001 and 2*eps, respectively (eps = 2^(-52)), which leaves you a lot of room. I would choose tol = 10^(-12) in your case.

Sign in to comment.