How to avoid creating lots of variables from calculation from a table
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi All,
I am still a beginner at this...
I have a table of data (dataTable) that the code below sets up, the point being there is a variable name ('Var') and a suffix of 1 to 10 in this example. From 'dataTable' I want to calculate the mean of a defined section for each variable, and ends with compiling the results into one array.
Is there a way to do this without having to create all the separate variables meanVar1...meanVar10 as below from the dataTable? Thanks and much appreciated.
Time = [0;1;2;3;4;5;6;7;8;9;10];
Var1 = randi([-10 10],1,11)';
Var2 = randi([-10 10],1,11)';
Var3 = randi([-10 10],1,11)';
Var4 = randi([-10 10],1,11)';
Var5 = randi([-10 10],1,11)';
Var6 = randi([-10 10],1,11)';
Var7 = randi([-10 10],1,11)';
Var8 = randi([-10 10],1,11)';
Var9 = randi([-10 10],1,11)';
Var10 = randi([-10 10],1,11)';
dataTable = table(Time, Var1, Var2, Var3, Var4, Var5, Var6, Var7, Var8, Var9, Var10);
meanVar1 = mean(dataTable.Var1(3:7));
meanVar2 = mean(dataTable.Var2(3:7));
meanVar3 = mean(dataTable.Var3(3:7));
meanVar4 = mean(dataTable.Var4(3:7));
meanVar5 = mean(dataTable.Var5(3:7));
meanVar6 = mean(dataTable.Var6(3:7));
meanVar7 = mean(dataTable.Var7(3:7));
meanVar8 = mean(dataTable.Var8(3:7));
meanVar9 = mean(dataTable.Var9(3:7));
meanVar10 = mean(dataTable.Var10(3:7));
meanscompilation = [meanVar1;meanVar2;meanVar3;meanVar4;meanVar5;meanVar6;meanVar7;meanVar8;meanVar9;meanVar10];
댓글 수: 0
채택된 답변
Steven Lord
2023년 5월 23일
If all the variables you want to add to the table array are the same type, create one array and use array2table or (given that you have time data) perhaps array2timetable.
Time = [0;1;2;3;4;5;6;7;8;9;10];
VarData = randi([-10 10], 11, 10);
names = ["Time", "Var"+(1:10)];
dataTable = array2table([Time, VarData], 'VariableNames', names)
Since your release predates the introduction of the ability to perform math on tables directly (release R2023a) I'd use varfun.
M = varfun(@mean, dataTable)
If upgrading to release R2023a or later is an option:
M23a = mean(dataTable)
Note that both these approaches by default will also operate on the Time variable in dataTable. You could specify InputVariables when calling varfun to skip operating on Time.
M = varfun(@mean, dataTable, 'InputVariables', 2:width(dataTable))
추가 답변 (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!