All Indices of all Numbers in Array
Ältere Kommentare anzeigen
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
Antworten (1)
Adam
am 6 Mär. 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 Kommentare
Adam
am 7 Mär. 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.
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!