MATLAB: How can i sort data using logical indexing

logical indexingsorting data

problem: i have two arrays: the first one is of unknown lenght and has two columns, one containing the data that i want to add to my second array and one containing a natural number (ranging from 1 to unknown) looking like this:
[ 0] [3]
[ 0] [5]
[ 3.36] [ 2]
[ 0.00100000000000122] [ 6]
[0.000999999999999446] [ 4]
[0.000999999999999446] [ 2]
my second array is empty. now i want to add the values (first columns) to the associated row ( second column) in my second array. There are multiple values for each row. the output of the second array should look like this:
[] []
[3.36] [0.00099999999446]
[0] []
[0.0009999999999446] []
[0] []
[0.00100000000000122] []
Is there a way to do this using logical indexing? It would be nice if i could avoid using for loops with if statements
Thanks.

Best Answer

Redistributing your numbers in the row indicated by the second column is very easy with accumarray:
a = [0 3
0 5
3.36000000000000 2
0.00100000000000122 6
0.000999999999999446 4
0.000999999999999446 2];
b = accumarray(a(:, 2), a(:, 1), [], @(v) {v.'})
This creates a 1d (column) cell array where each row is all the numbers corresponding to that particular row index. Each row is just long enough to store the required numbers
The problem comes from you wanting a 2d cell array instead. To be honest, I'm not sure there's any advantage in it and it requires more work. One way of generating it:
%continuing from above
maxcols = max(cellfun(@numel, b)); %or you could get that from the histogram of a(:, 2)
c = cellfun(@(v) [num2cell(v), cell(1, maxcols - numel(v))], b, 'UniformOutput', false);
c = vertcat(c{:})