Define a collection of variables
3 次查看(过去 30 天)
显示 更早的评论
Suppose I have a table
date visitor city dummy_for_January dummy_for_February dummy_for_March
----------------------------------------------------------------------------------------------------------
I want to define a collection of such dummy variables so that I do not need to write them one by one each time. Please advise.
2 个评论
Cris LaPierre
2021-1-16
Assuming you already have a table defined, you can extract the variable names from the table and store them in a variable.
varNames = table.Properties.VariableNames
You can then save that variable to a mat file if you want to have the variable accessible from one matlab session to the next.
Image Analyst
2021-1-16
I have no idea. To create a variable, you're going to have to write it - you'll have to see its name down in your script somewhere, which means you typed it. It won't just magically create itself somehow without being written. Try this:
采纳的回答
Matt J
2021-1-17
Since you already have the data in table form, you can just do things like,
mdl=fitlm(T(:,["Albania","Afghanistan","sales"]))
5 个评论
Matt J
2021-1-17
First, create a copy of the table containing only the countries,
Tcountries=T;
Tcountries(:,["population" "area" "income"])=[]; %discard non-country variables
Now, you can do things like,
mdl1=fitlm([Tcountries, T(:,"population")]);
mdl2=fitlm([Tcountries, T(:,"area")]);
mdl3=fitlm([Tcountries, T(:,"income")]);
更多回答(1 个)
Walter Roberson
2021-1-16
mons = {'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'};
vars = [string({'date', 'visitor', 'city'}), "dummy_for_" + string(mons)];
nvars = length(vars);
T = array2table(zeros(0,nvars), 'VariableNames', vars)
T.Properties.VariableNames
3 个评论
Steven Lord
2021-1-17
There are a number of different ways to retrieve data from a table array. Let's make a sample table.
load patients
patients = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);
head(patients)
I can retrieve variables to a normal double array using curly braces and specifying the variables either by name or by number.
T1 = patients{1:8, ["Age", "Height", "Weight"]}
T2 = patients{1:8, 3:5}
Or I can find all variables whose names end with the letter t (as a bit of a silly example.) Note here I'm indexing into the patients table with parentheses so the result is a table (with variable names.)
VN = patients.Properties.VariableNames;
T3 = patients(1:8, endsWith(VN, 't'))
You could use startsWith, endsWith, contains, or other string processing functions to select specific variables from your table.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!