How to index a matrix in matlab
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Stephen23
il 18 Apr 2017
Modificato: Stephen23
il 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
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!