Slicing 2D array based on conditions specified in a seperate list
이전 댓글 표시
I have 2D (NxM) matrix with N rows and M columns (the dimensions depend on experimental data I collect, for example see matrix A below:
A = [1 0 0 1 0; 0 1 0 1 0 ; 1 0 0 1 1; 0 0 0 1 1]
Information about the identity of each row is specified by another Nx1 column vector, for example see matrix L below.
L = [A1 C4 F7 E5]*
So, row 1 of matrix A belongs to group "A1", row 2 belongs to group "C4" and so on.
I would like to create a slice of matrix A that contains specific rows that I specify from vector L.The grouping terms depend on experimental data, but I would like the ability to generate a series of slices based on specific elements of vector L that I define.
For example, I would like slice of matrix A containing only groups "A1" and "F7" from vector L to form the in a new 2xM matrix S. :
S = [1 0 0 1 0; 1 0 0 1 1]
I would appreciate some advice on how to do generic slicing of matrix A by using a subset of group identifiers from vector L. Any feedback would be much appreciated.
채택된 답변
추가 답변 (1개)
Keys = {'A1', 'C4', 'F7', 'E5'};
Data = [1 0 0 1 0; 0 1 0 1 0 ; 1 0 0 1 1; 0 0 0 1 1];
WantedKeys = {'A1', 'F7'};
[found, index] = ismember(WantedKey, Keys);
WantedData = Data(index, :)
[EDITED] Taken from Stephen Coboldick's comment: If the Keys are not unique, the order of the arguments for ismember are changed:
Keys = {'A1', 'C4', 'F7', 'A1'};
WantedKeys = {'A1', 'F7'};
Data = [1 0 0 1 0; 0 1 0 1 0 ; 1 0 0 1 1; 0 0 0 1 1];
index = ismember(Keys, WantedKeys);
Result = Data(index, :)
ans =
1 0 0 1 0
1 0 0 1 1
0 0 0 1 1
댓글 수: 3
Tal Sharf
2017년 2월 3일
>> Keys = {'A1', 'C4', 'F7', 'A1'};
>> WantedKeys = {'A1', 'F7'};
>> Data = [1 0 0 1 0; 0 1 0 1 0 ; 1 0 0 1 1; 0 0 0 1 1];
>> index = ismember(Keys,WantedKeys);
>> Data(index,:)
ans =
1 0 0 1 0
1 0 0 1 1
0 0 0 1 1
@Tal Sharf: note that Jan Simon's solution is a much better concept than doing this in a loop.
Tal Sharf
2017년 2월 6일
카테고리
도움말 센터 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!