Basic Question: How to index into table by a text column
Show older comments
Hello, new to Matlab. I have a table imported into Matlab. How to I extract all data in all columns from that table in only the rows labelled "hardness"? I do know that I can't extract from a table (at least I think I can't). I was able to convert the table to a cell array but I am still unable to figure out how to get just the rows with the text label "hardness" out of this table.
3 Comments
A table does not have labels. You possibly have one of the columns containing strings that can be interpreted as labels, but you haven't told us the name of that column.
Note that there is absolutely no need to convert a table to a cell array. You can do filtering directly on tables.
dpb
on 10 Oct 2016
Not by the name labels, no, but it does have the .RowNames property which I'd presume qualifies in concept to OP???? At least, that'd be my guess...
Guillaume
on 10 Oct 2016
Except that you can't have two rows with the same name, so you wouldn't be able to select only the rows labelled "hardness" since there'll be at most one.
Accepted Answer
More Answers (1)
To return all rows of a table whose column somecolumnname matches a specific string:
filteredtable = yourtablename(strcmp(yourtablename.somecolumnname, stringtomatch), :);
e.g.
t = table({'hardness', 'aaaa', 'hardness', 'bb'}', [1;2;3;4], [pi; exp(1); log(2); 0], 'VariableNames', {'label', 'value', 'someothername'})
filteredt = t(strcmp(t.label, 'hardness'), :)
edit: since we now know that the label column is the 4th, you can do this:
filteredtable = yourtable(strcmp(yourtable{:, 4}, 'hardness'), :) %keep only those rows whose 4th column is 'hardness'
2 Comments
Peter Perkins
on 13 Oct 2016
This sounds like a good candidate for using a categorical variable rather than text. That would allow a syntax such as
filteredtable = yourTable(yourTable.yourVar == 'hardness', :)
which you might find more readable. Note also using dot subscripting (yourTable.yourVar) rather than braces. For one variable, that's a simpler way to go.
dpb
on 13 Oct 2016
Yeah, until I reread the doc's that's how I thought the .name property would work...
Categories
Find more on Tables 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!