0

I have a column of numbers, and I want to find those that are greater than 10 and then record their indices. I can do that for a single index with:

[y, I] = A(A>10)

where y stores the values, I stores the index, and A is the matrix name.

but MATLAB won't let me do it for more than one index. When I tried, it gave me the error:

"Indexing cannot yield multiple results. "

Any help would be greatly appreciated because I am very new to MATLAB and haven't figured out all the tricks yet.

bool.dev
  • 17,508
  • 5
  • 69
  • 93
  • 1
    related question: [How to select a submatrix (not in any particular pattern) in Matlab](http://stackoverflow.com/questions/13091193/1336150#13093242) (see the part about logical indexing) – Eitan T Aug 29 '13 at 08:06

1 Answers1

1

You are asking matlab to return multiple results, while A(A>10) would return only a column matrix. This would be one right way to do it:

I = A > 10;
y = A(I);

Or if you want them in a single line, you can do this:

[y, I] = deal(A(A>10), A>10);
Prashanth
  • 1,252
  • 2
  • 13
  • 28
  • Thank you that did it. We haven't gone over the deal function yet. – Karun Dhillon Aug 29 '13 at 06:22
  • There's really no point in making a one-liner here. Readability is more important! – Eitan T Aug 29 '13 at 08:02
  • I had another quick question regarding this: instead of the elements in A>10, how would I format this to index the three greatest values? – Karun Dhillon Aug 29 '13 at 18:23
  • For that you need to use [sort()](http://www.mathworks.in/help/matlab/ref/sort.html) – Prashanth Aug 30 '13 at 14:21
  • Hint: if A is a 2D matrix, use the command A(:) to read it columnwise as a 1D matrix before using sort(). Also refer to the question which @EitanT has suggested to learn more about indexing. – Prashanth Aug 30 '13 at 14:28