Use variable to find column in table
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I am trying to reset a tables values to 0.
The sceanario may change every time. So I am using table.Properties.VariableNames to find the names of the columns and then I was trying to cycle through the columns using the names stores in table.Properties.VariableNames so I could assign the reset values.
For example, I have a table with 5 columns called A to E
var=table.Properties.VariableNames
var={'A','B','C','D','E'}
table.var(1)=zeros(size(table.var(1)))
The error is that var is not a table column name which is true, but what is stored inside var is. I have to do it like this as one of the columns is actually a mini table and using size(table(:,10)) gives 12 1 but its actually 12 4. using size(table.var10) gives the correct answertab
1 commentaire
Stephen23
le 13 Déc 2023
You can either use T{:,X} or T.(X) to access any variable using expression X.
Réponse acceptée
Voss
le 13 Déc 2023
% a table with 5 columns, one of which is a table with 4 columns:
t = table(rand(12,1),rand(12,1), ...
array2table(rand(12,4),'VariableNames',"C"+(1:4)), ...
rand(12,1),rand(12,1), ...
'VariableNames',{'A','B','C','D','E'});
var = t.Properties.VariableNames;
disp(t)
Use this syntax to refer to a table column's contents when the column names are stored in var:
t.(var{1})
t.(var{3})
Using that, here is one way to set everything to 0:
for ii = 1:numel(var)
if istable(t.(var{ii}))
t.(var{ii}){:,:} = 0;
else
t.(var{ii})(:) = 0;
end
end
disp(t)
2 commentaires
Plus de réponses (2)
Mathieu NOE
le 13 Déc 2023
hello
maybe this ? here we want to reset the B column
m = 10,
n = 3;
t = array2table(rand(m,n),'VariableNames',{'A' 'B' 'C'})
var=t.Properties.VariableNames;
col2reset_name = "B";
index = find(contains(var,col2reset_name));
t(:,2) = array2table(zeros(m,1))
0 commentaires
Steven Lord
le 4 Jan 2024
Note that as shown on the documentation page linked to by @Stephen23, you can access data in a table using variable names, logical arrays, or subscripts.
A = array2table(magic(4))
B1 = A.Var3
B2 = A{:, "Var3"}
B3 = A{:, 3}
B4 = A{:, [false false true false]}
Converting a subset of a list of variable names in a table to either subscripts (as B3) or a logical mask (as B4) is pretty easy.
varnames = ["Var2", "Var4"]
mask = ismember(A.Properties.VariableNames, varnames)
subscripts = find(mask)
0 commentaires
Voir également
Catégories
En savoir plus sur Tables dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!