Reputation: 327
My question may be a bit "silly", but I am stucked here, so I would really need your help.
So, we have a cell array Q 5520x1, like the one below:
I'm only interested in the first two numbers of each row. To be specifically clear, giving
K>> Q{1}
ans = 0 1 0 238
I only care about 0 and 1, and so on with the other rows. Only the first two numbers of each row. Let's just ignore the rest values in each row of Q, they are more or less irrelevant.
My problem is, how is it possible to check if the first value of each row in the cell array Q, in the example above 0, remains the same? What I would like to achieve, is while the first value is the same, I want to store in another cell array, all the second values. In case of number 0, I want to store the values
[1,3,127,129,216,217,252,253,302,303,342,343]
and so on. How could this be done?
Any help or advice would be really appreciated.
Upvotes: 0
Views: 197
Reputation: 2334
% Example Q
Q = {[0 1 135 134];
[0 3 154 26];
[0 16 146 234];
[1 2 324 125];
[1 7 213 252]};
A = cell2mat(Q(1:2760));
[~,~,ind2] = unique(A(:,1));
C = arrayfun(@(x)A(find(ind2==x),2),1:max(ind2),'UniformOutput',false);
C{1}
ans =
1
3
16
C{2}
ans =
2
7
Upvotes: 2
Reputation: 112769
You can use unique
and accumarray
as follows:
Q = {[0 1 0 238]
[0 3 1 84]
[1 2 1 85]
[3 4 5 6]}; %// example data. Cell array of equal-size row vectors
Qm = vertcat(Q{:}); %// convert Q into matrix
[vals, ~, id] = unique(Qm(:,1)); %// get unique id for 1st col
result = accumarray(id, Qm(:,2), [], @(x){x.'}); %'// gather 2nd col values according to id
This gives:
vals =
0
1
3
result{1} =
1 3
result{2} =
2
result{3} =
4
Upvotes: 2
Reputation: 1048
You can do it with a for loop :
cell_range = max(cellfun(@(x) x(1),Q));
C = cell(cell_range,1)
for i = 1:length(Q)
M = Q{i};
disp(M(1));
C{M(1)} = [C{M(1)}, M(2)];
end
Upvotes: 0