Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding value to a cell element specified by array

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

like image 495
The Minion Avatar asked Apr 17 '26 12:04

The Minion


2 Answers

Use accumarray:

 out = accumarray(idx(:),val(:),[],@(x){x},{});
like image 181
Jonas Avatar answered Apr 19 '26 10:04

Jonas


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.

like image 41
Daniel Avatar answered Apr 19 '26 09:04

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!