remove row from matrix
2 views (last 30 days)
Show older comments
Jakob Hannibal
on 31 Oct 2014
Commented: Jakob Hannibal
on 4 Nov 2014
Hello!
I have a problem where I need to remove som rows from a matrix. I need to remove all numbers under 10 and over 60 from the first row and all negative numbers from the second row. The third row has to be between 1:4. I need to print if a row has been removed, so I know which rows are missing, which I haven't implemented in the code below. I have tried in many ways and has come up with this that removes the right rows, but I am sure it can be done in a smarter way…
clc;clear; false_data = [8 20 15 35 65 35; 0.1090 -0.50 0.5170 1.0860 0.9340 0.1090;1 2 3 4 6 1]'; approved_bacteria = [1 2 3 4];
for i = 1:length(false_data(:,1)) indices = 10 > false_data(:,1) | (false_data(:,1) > 60)
false_data(indices,:) = []; end
for i = length(false_data(:,2)) indices = false_data(:,2) < 0; false_data(indices,:) = []; end
for i = length(false_data(:,3)) indices = false_data(i,3) < 1 false_data(i,3) > 4; false_data(indices,:) = []; end false_data
0 Comments
Accepted Answer
Sean de Wolski
on 31 Oct 2014
This is how I'd do it.
% Bounds
lb = [10 0 1];
ub = [60 inf 4];
% Simulate data
n = 1000;
data = [randi(100,[n,1]) randn(n,1) rand(n,1)*10];
% Apply conditions
idxrmv = any(bsxfun(@lt,data,lb) | bsxfun(@gt,data,ub),2);
% Remove
data(idxrmv,:) = [];
% print
fprintf('Removed row %3.0i\n',find(idxrmv));
5 Comments
Sean de Wolski
on 31 Oct 2014
loop over the rows of the matrix, find the columns in each row, print.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!