How can I use a user input to pull a column from a timetable?
조회 수: 23 (최근 30일)
이전 댓글 표시
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
채택된 답변
Steven Lord
2022년 2월 4일
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
추가 답변 (1개)
Davide Masiello
2022년 2월 4일
편집: Davide Masiello
2022년 2월 4일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!