Use variable to find column in table
조회 수: 30 (최근 30일)
이전 댓글 표시
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
Stephen23
2023년 12월 13일
You can either use T{:,X} or T.(X) to access any variable using expression X.
채택된 답변
Voss
2023년 12월 13일
% 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개)
Mathieu NOE
2023년 12월 13일
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
Steven Lord
2024년 1월 4일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!