MATLAB: Create an array from a cell array

MATLAB

Given the following cell array
G= {[1 2 1 2 3 4 5 4 5 4 6 3 9 3 9;
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75],
[1 1 1 1 2 3 4 4 4 5 4 6 3 6 3 9;
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80]}
and consider just G {1,1} (then I will need to iterate to consider also G{1,2})
I want to obtain theese arrays
V1=[1 1 ; 5 0];
V2=[2 2; 10 0];
V3=[3 3 3; 25 0 0];
V4=[4 4 4; 30 0 0]
V5=[5 5, 35 0]
V6=[6; 55]
V7=[9 9, 65 0]
Visualizing G{1,1}
I want to obtain 7 arrays, because 7 is the number of different elements that are inside the first raw of G{1,1}: (1 2 3 4 5 6 9). If the number of diversities is more x, I would like to obtain x arrays.
Then each vector has, in the first raw, the elements repeated as many times as they are inside the first raw of G{1,1}. Instead, in the second raw of each arrays we want to have as many zeros as the columns above, but in the first position (first column, second raw) we want to report the value that is present in the second raw of G{1,1} when the element appear for the first time.
For example, the element 9 appear the first time with value 65, so in V9 we will have 65, as indicated by yellow circles in the figure above.
May someone help me?

Best Answer

For just one element of the cell array, eg. G{1}:
[uval, loc1, ids] = unique(G{1}(1, :)); %get unique values of first row, with location where first occurence is found and unique id for each values
count = accumarray(1, ids)'; %get histogram (count) of each unique value
result = arrayfun(@(v, s, n) [repelem(v, n); s, zeros(1, n-1), uval, G{1}(2, loc1)], count, 'UniformOutput', false);
celldisp(result)
To apply to each element of G just wrap it in a loop:
result = cell(size(G));
for gidx = 1:numel(G)
[uval, loc1, ids] = unique(G{gidx}(1, :));
count = accumarray(ids, 1)';
result{gidx} = arrayfun(@(v, s, n) [repelem(v, n); s, zeros(1, n-1)], uval, G{idx}(2, loc1), count, 'UniformOutput', false);
end