How do I make a variable that is equal to the position of a row in a table by using the name of that row?

16 views (last 30 days)
I have this
find(ismember(fieldnames(T), 'Name of Column'))
Where T is a table with named rows and columns, if I enter the name of a column it gives me a number equal to the position of that column, but it does not work for rows. How could I make this work for rows as well?

Accepted Answer

dpb
dpb on 27 May 2020
Edited: dpb on 28 May 2020
fieldnames is specically documented for struct or Java or COM objects at least thru R2019b; I wasn't aware it would return the column names from a table object. There's no parallel for the row identifiers like rownames however.
fieldnames seems to return the table variable names first and is followed by the elements {'Properties','Row','Variables'} irrespective of the values of those additional property values. Hence, it's not particularly useful for that purpose.
But, it's simple enough, just use the table .Row property...
find(ismember(T.Row, 'Name of Row'))
There is also the T.Properties.RowNames property that returns the row names cellstr array.
I tend to write using newer string class functions like contains or beginsWith instead of ismember although the row names internally are and are returned as a cellstr array.
  4 Comments
dpb
dpb on 27 Sep 2023
Edited: dpb on 27 Sep 2023
"I keep looking in matlab answers/questions and tutorials explanations on how to work witth tables and arrays..."
Well, going directly to the horse's mouth doc for table would have led you to the example at <Setting rownames example>.
The RowNames property is metadata, a field in the table .Properties just like .VariableNames. Isn't used as often and is optional (whereas .VariableNames are required) so may get overlooked even by relatively experienced users.
dpb
dpb on 27 Sep 2023
Edited: dpb on 28 Sep 2023
"I want to settle the first column categories as rowNames to index the variables according to these rows (each corresponding to a different experiment)."
You may find keeping the experiment name/number as the variable instead of as row names more convenient for analysis by experiment and other possible groupings; rowfun uses only 'GroupingVariables' as the grouping input, it doesn't allow to use 'RowNames' as a grouping criterion. It and alternative ways with groupsummary or grpstats or findgroups don't use anything other than variables for grouping. You can always do looping and manually select the various row names and get to the end result using them, but may not be the simplest route to an end.
ADDENDUM: Of course, nothing says you can't do both -- keep as variable and use as rownames.

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!