필터 지우기
필터 지우기

How to index a matrix in matlab

조회 수: 3 (최근 30일)
Amy Xu
Amy Xu 2017년 4월 18일
편집: Amy Xu 2017년 5월 23일
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
Amy Xu
Amy Xu 2017년 4월 18일
편집: Amy Xu 2017년 4월 18일
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 2017년 4월 18일
Any solution? @Jan Simon

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2017년 4월 18일
편집: Stephen23 2017년 4월 18일
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개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by