Basic Question: How to index into table by a text column
显示 更早的评论
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 个评论
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
2016-10-10
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
2016-10-10
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.
采纳的回答
更多回答(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 个评论
Peter Perkins
2016-10-13
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
2016-10-13
Yeah, until I reread the doc's that's how I thought the .name property would work...
类别
在 帮助中心 和 File Exchange 中查找有关 Tables 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!