How can I use a user input to pull a column from a timetable?
19 views (last 30 days)
Show older comments
I am trying to pull one column of data using from a timetable using a user input. I can easily pull one column from a timetable using the raw code, but I cannot get it to work with a user input. Here's a snippet of code:
RawTime=[seconds(T.Time)];
prompt1='Enter the EXACT name of variable to view (ie. status_State):';
%%idk=input(prompt1,'s'); ignore this line
TM=T.input(prompt1,'s');
Matrixx=[RawTime,TM];
Everytime I try the above method I get a reasonable error: Unrecognized table variable name 'input'. Which does and doesnt make sense to me, because i thought it would use the input of the user rather than the literal word input.
Now I can get the "status_State" column manually if I do this:
RawTime=[seconds(T.Time)];
%%prompt1='Enter the EXACT name of variable to view (ie. status_State):';
%%idk=input(prompt1,'s'); ignore this line
TM=T.status_State;
Matrixx=[RawTime,TM];
But I want to make that a user input since there are multiple columns that a user should be able to choose from.
1 Comment
Accepted Answer
Steven Lord
on 4 Feb 2022
Whenever you write T.foo where T is a table, that only works if T has a variable literally named foo (with one exception, Properties, which is not allowed as a table variable name. I don't think there are any other exceptions.)
Two ways to do what you want:
% Make a sample table
load patients
T = table(LastName, Age);
T = T(1:8, :)
You can use the dynamic variable names syntax. With this, MATLAB will interpret whatever the expression inside the .() operator evaluates to as the name of the table variable to retrieve. I hard-coded L but you could use input if you wanted. You might instead want to bring up a listbox dialog (with listdlg) populated using T.Properties.VariableNames and use whatever the user selects from there as your index. Then if they select a name they have to select one of the table's variable names.
V = T.Properties.VariableNames
% L = V{1}
L = 'LastName';
lastNames1 = T.(L)
The second approach is to use brace indexing.
lastNames2 = T{:, L}
0 Comments
More Answers (1)
Davide Masiello
on 4 Feb 2022
Edited: Davide Masiello
on 4 Feb 2022
Not sure this is the most elegant solution, but it does work
RawTime = [seconds(T.Time)];
prompt1 = 'Enter the EXACT name of variable to view (ie. status_State):';
idk = input(prompt1,'s');
index = find(contains(T.Properties.VariableNames,idk));
TM = T{:,index};
Matrixx = [RawTime,TM];
On a different aspect: when you use 'seconds', you assign the class duration to RawTime. When creating Matrixx, TM gets also converted into duration, as you can't have elements of different classes in an array. Be sure that's fine for you before proceeding.
See Also
Categories
Find more on Logical 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!