Use variable to find column in table
30 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Stephen23
il 13 Dic 2023
You can either use T{:,X} or T.(X) to access any variable using expression X.
Risposta accettata
Voss
il 13 Dic 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)
Più risposte (2)
Mathieu NOE
il 13 Dic 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 Commenti
Steven Lord
il 4 Gen 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 Commenti
Vedere anche
Categorie
Scopri di più su Tables in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!