How to index a matrix in matlab

1 view (last 30 days)
Amy Xu
Amy Xu on 18 Apr 2017
Edited: Amy Xu on 23 May 2017
Assume input matrix I as follows:
I = [
100 56 1
100 54 1
100 65 1
101 5 0
101 10 1
101 15 1
101 20 0
101 30 1
101 20 1
101 50 1
198 30 0
198 20 1
203 10 0
203 5 1
203 60 1
203 20 1
203 15 1
44 70 0
44 65 1
44 45 1
44 50 0
44 35 1
44 35 1
44 50 0
44 70 1
44 75 1
44 65 1
];
I want to create 3 matrix based on the I matrix:
Matrix A:
Based on the unique ID in first column of matrix A, I want to generate numbers if ID is same then corresponding cell get same number and if the ID changed, the corresponding ID reset numbers. Also, if in the same ID number, from the third column in matrix I, there was an interrupt with value 0, then number reset and continue (see the figure below).
Matrix B:
Based on the out put of matrix A, I want to count how many number generated for every ID (and if there was an interrupt with 0). See the figure below.
Matrix C:
Based on the out put of matrix A, I want to sum up the corresponding cells from second column in matrix I. See the figure below.
A = [
100 1
100 1
100 1
101 1
101 1
101 1
101 2
101 2
101 2
101 2
198 1
198 1
203 1
203 1
203 1
203 1
203 1
44 1
44 1
44 1
44 2
44 2
44 2
44 3
44 3
44 3
44 3
];
B = [
100 3
101 3
101 4
198 2
203 5
44 3
44 3
44 4
];
C = [
100 175
101 30
101 120
198 50
203 110
44 180
44 120
44 260
];
  5 Comments
Amy Xu
Amy Xu on 18 Apr 2017
Edited: Amy Xu on 18 Apr 2017
Let me give you an example. Consider ID number 44 in the figure. In matrix I, look at the third column. There are three 0. It means that in output matrix A, we should have three set numbers {1,2,3}. If you look at matrix A for ID 44 and second column, you can see that the first three is given by 1, the second three is given by 2 and the third part is given by 3.
Is that clear?
Thanks!
Amy Xu
Amy Xu on 18 Apr 2017
Any solution? @Jan Simon

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 18 Apr 2017
Edited: Stephen23 on 18 Apr 2017
Array A
>> [U,X,Y] = unique(I(:,1));
>> [~,X] = sort(X);
>> [~,X] = sort(X);
>> fun = @(v){cumsum(v==0)+(v(1)==1)};
>> Z = accumarray(X(Y),I(:,3),[],fun);
>> A = [I(:,1),cell2mat(Z)]
A =
100 1
100 1
100 1
101 1
101 1
101 1
101 2
101 2
101 2
101 2
198 1
198 1
203 1
203 1
203 1
203 1
203 1
44 1
44 1
44 1
44 2
44 2
44 2
44 3
44 3
44 3
44 3
Array B
>> V = [true;any(diff(A,1,1),2)]
>> W = accumarray(cumsum(V),ones(size(V)));
>> B = [I(V,1),W]
B =
100 3
101 3
101 4
198 2
203 5
44 3
44 3
44 4
Array C
>> T = accumarray(cumsum(V),I(:,2));
>> C = [I(V,1),T]
C =
100 175
101 30
101 120
198 50
203 110
44 180
44 120
44 260

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!