Check for value in multiple columns and delete rows with that value
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Karena Weduwen
am 27 Nov. 2017
Beantwortet: Star Strider
am 27 Nov. 2017
I have a variable with six columns (A-F) and n rows. Whenever column C is -1 i want to look up the value in column A of the same row and delete all rows with that value.
0 Kommentare
Akzeptierte Antwort
Star Strider
am 27 Nov. 2017
If ‘M’ is your matrix, this will work:
idx = any(bsxfun(@eq, M(:,1), (M(M(:,3)==-1,1))'),2);
Mout = M(~idx,:);
The ‘M(M(:,3)==-1,1)’ checks column 3 for -1 values, and returns the corresponding values in column 1. The bsxfun call searches for elements of column 1 that are equal to those values, and returns a matrix of column vectors of logical indices for each equality. The any call will be 1 if any of the column vectors are 1 in all rows, creating a single column logical vector from the matrix of logical vectors. Then the ‘Mout’ assignment returns all the rows that are not 1, producing the desired output.
Also, you can avoid retyping the ‘idx’ assignment with your actual array name by creating an anonymous function from it, so that if you call your array ‘A’:
idxfcn = @(M) ~any(bsxfun(@eq, M(:,1), (M(M(:,3)==-1,1))'),2);
idx = idxfcn(A);
Result = A(~idx,:);
producing the desired result.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!