Reputation: 95
My question should be fairly easy, but I can't get it to work. I want to take from a matrix only the relevant rows by using logical operators and then storing those rows only. I'm used to doing this with a for-loop in other languages, but in Matlab it should be faster to run this over the entire array or matrix at once.
This is an example of what I think should work, but all my similar attempts generate different errors, and I'm not sure what to do.
Mrelevant = Matrix(Matrix.no_refs > 100)
Edit: Matrix is actually a table with headers, I want to keep only the rows that fulfil certain requirements, like the value in the column with header 'no_refs' should be above 100.
I hope this is clear enough, thanks!
Upvotes: 1
Views: 131
Reputation: 125874
Now that you specified Matrix
is a table
, the answer is clear. You forgot an additional colon index argument to include all variables for the given rows you are selecting:
Mrelevant = Matrix(Matrix.no_refs > 100, :);
This will give you a new table Mrelevant
that includes only those rows from Matrix
where the no_refs
variable is greater than 100. See here for all of the ways to access data in a table
by row and/or variable.
Upvotes: 2
Reputation: 370
The syntax you are showing here should work, though I do not know what the purpose of the no_refs
might be. The correct syntax is:
Mrelevant = matrixName(matrixName > 100)
However, this will create a single column containing the values that meet the condition. For example,
testMatrix =
0.8147 0.0975 0.1576 0.1419 0.6557
0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 0.8491
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
relevant = testMatrix(testMatrix > .5)
relevant =
0.8147
0.9058
0.9134
0.6324
0.5469
0.9575
0.9649
0.9706
0.9572
0.8003
0.9157
0.7922
0.9595
0.6557
0.8491
0.9340
0.6787
However, when you say
only the relevant rows by using logical operators and then storing those rows
do you mean storing only rows where all elements in the row meet the condition? In that case, the syntax would be
relevant = testMatrix
% Delete all rows that don't meet the requirement
relevant(any(relevant<=100, 2),:) = [];
This will simply erase any row containing values that don't meet your requirement.
Upvotes: 0