Adding a value to a cell element specified by an array

I'm looking for a vector solution!

I have two arrays, for example:

idx=[1 1 1 2 2 3 3 4 4 4 5 5 6 7 8 8 8 9 9]; %%//Integers,sorted
val=[1 4 8 2 5 3 9 1 4 8 2 5 6 7 1 4 8 3 9]; %%//respective Values (could be anything)

      

Now I want to create a cell array that contains the idx

corresponding values in its elements val

. So the result should be [9x1] cell

with:

[1 4 8]
[2 5]
[3 9]
[1 4 8]
[2 5]
[6]
[7]
[1 4 8]
[3 9]

      

I know that I could iterate over values ​​from 1 to 9 and use horzcat while idx is equal to my loop index, but I am looking for a vectorized solution. The reason is that I am trying to change the problem loop solution to a vectorized solution, but I am stuck here

+3


source to share


2 answers


Use accumarray

:



 out = accumarray(idx(:),val(:),[],@(x){x},{});

      

+7


source


mat2cell(val,1,diff([0,find(diff(idx)),numel(idx)]))

      



Perhaps someone will find a way to get rid of find

, and then, most likely, faster.

+4


source







All Articles