All Indices of all Numbers in Array

1 view (last 30 days)
Hannes
Hannes on 6 Mar 2015
Commented: Adam on 7 Mar 2015
Lets say I have an array that looks something like this:
A = [3 2 1;...
5 1 2;...
1 3 5]
I want to know in which row every number can be found in A my result should look like this:
ind = [1 2 3;...
1 2;...
1 3;...
0;...
2 3]
so e.g. 1 can be found in row 1, 2 and 3, 4 can't be found in any row and so on
I'm struggling with linear indexing because I dont search for a specicif value. Solution with a loop works, but is way too computationally intensive for my purposes.
Thanks in advance
  2 Comments
Adam
Adam on 6 Mar 2015
I assume the 3rd row of ind should be
1 3
?

Sign in to comment.

Answers (1)

Adam
Adam on 6 Mar 2015
maxElem = max( A(:) );
res = cell( maxElem, 1 );
for i = 1:max( A(:) )
res{i} = ceil( find( A' == i ) / 3 );
end
gives the correct answer, in a cell array because there aren't the same number of results per row and with a [] instead of 0 where the number does not appear at all.
Not sure if it is doable without a loop though...maybe...
  2 Comments
Hannes
Hannes on 7 Mar 2015
Edited: Hannes on 7 Mar 2015
not exactly what i was hoping for, but i guess there is no better answer.
thanks!
Adam
Adam on 7 Mar 2015
The use of cell arrays makes any code ugly, but they are convenient for operations like this.
The for loop really shouldn't be seen as a problem though. Achieving something like this without a for loop could be possible, but it is not trivial and you have to question what would be the purpose. Vectorisation is always better than a for loop, but some other fancy syntaxes just to avoid a for loop are often not.
Two of the biggest misconceptions from people working with Matlab seem to be at opposite ends of the spectrum:
  • I need to do something on a multi-dimensional array, I'll use nested for loops.
  • For loops are always bad in Matlab, I should do everything possible to avoid them.
If you can't vectorise a for loop is usually perfectly fine.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!