Slicing 2D array based on conditions specified in a seperate list
Show older comments
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.
Accepted Answer
More Answers (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 Comments
Tal Sharf
on 3 Feb 2017
>> 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
on 6 Feb 2017
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!