0

What I'd like to do is get Matlab to generate a list of values starting at 0 and going up until the size of the array and so that when the value shows up it converts into this list of values.

For instance:

-0.7500 -0.5000 -0.2500 0 0.2500 0.5000 0.7500 1.0000

I want this to generate:

0 1 2 3 4 5 6 7

So that when I enter the value -0.75 it'll convert it to 0 and so on. I saw my teacher use a Matlab function that did this automatically but unfortunately he hasn't provided the name of the function (simply said it exists). In case no one knows this function I'll just write my one but I'd prefer something written by the Matlab developers.

DMH
  • 182
  • 1
  • 2
  • 17

1 Answers1

0

Let

 x = [-0.7500 -0.5000 -0.2500 0 0.2500 0.5000 0.7500 1.0000];
 value = -.75;

You can use

 find(value==x)-1 %// -1 needed because Matlab indexing starts at 1, not 0

or

ismember(value, x)-1

Beware of comparing floating-point values for equality, though. You might want to include a tolerance:

tol = 1e-6; %// relative tolerance
find(abs(value./x-1)<tol)-1

You could also use a map, although it seems overkill for this, and has the potential problem of floating-point comparison:

x = [-0.7500 -0.5000 -0.2500 0 0.2500 0.5000 0.7500 1.0000];
y = 0:numel(x)-1;
dict = containers.Map(x, y);

Then dict(-.75) returns 0, etc.

Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • While I've already implemented it like this I was hoping for a function in Matlab that did this automatically, thank you nonetheless. – DMH Sep 28 '14 at 16:27
  • Well, this use of `find` and `ismember` seems to me pretty automatic. You're calling those functions and not needing much more – Luis Mendo Sep 28 '14 at 16:28
  • Maybe you want a [map](http://www.mathworks.es/es/help/matlab/map-containers.html). It doesn't seem like the most adequate option here, though – Luis Mendo Sep 28 '14 at 16:36
  • I'd rather go for the `find` approach with a tolerance – Luis Mendo Sep 28 '14 at 20:27