问题描述:

I am trying to find what's the number on the array for the 1000 value. This is my code:

size = linspace(420, 2200, 100000);

size1000 = find(size==1000);

It returns an empty variable for size 1000. If I actually change 1000 with 420 it actually returns 1 like it should. Why is this not working?

网友答案:

The result of find is empty because 1000 is not in the array and isn't expected to be. Using the inputs to linspace, your expected step size is going to be 0.0178

(2200 - 420) / 100000
%   0.0178

With this step size and a starting value of 420, you're never going to hit the value 1000 exactly. The closest values in the array are 1000.001 and 999.983. If you want to identify values that are close to 1000, you can do something like the following instead.

inds = find(abs(size - 1000) < 0.01);

As a side-note, do not use size as the name of a variable since that is the name of a built-in MATLAB function and using it as a variable name can result in unexpected behavior.

网友答案:

You can also use logical indexing to simply remove all of the values below 1000, and then you know that the first component of what is left will be your answer....

a = size(size>1000);
a(1)

For what it is worth, please PLEASE do not use size as a variable name. size is an important MATLAB function to get the size of a matrix. For example,

>> size(randn(2,3))

ans =

     2     3

However, when you declare a variable named size, like you do in your code, you will hide this function. So now, at some point later in your code, if you called size(randn(2,3)), you will get the cryptic error

Subscript indices must either be real positive integers or
logicals.

These are extremely tricky to track down, so please avoid it.

相关阅读:
Top