I am looking for a vectorized 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 which contains in his elements specified by idx the according values of val. So the result should be a [9x1] cell with:
[1 4 8]
[2 5]
[3 9]
[1 4 8]
[2 5]
[6]
[7]
[1 4 8]
[3 9]
I know I could loop over the values from 1 to 9 and use horzcat while idx is equal to my loop index but I am looking for a vectorized solution. Reason is, that I am trying to change a loop solution of a problem to vectorized solution yet I am stuck here
Use accumarray:
out = accumarray(idx(:),val(:),[],@(x){x},{});
mat2cell(val,1,diff([0,find(diff(idx)),numel(idx)]))
Maybe someone finds a possibility to get rid of the find, then it's probably faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With