How to round values of table with mixed types?
조회 수: 15 (최근 30일)
이전 댓글 표시
I would like to round all values in given columns, but get the error To assign to or create a variable in a table, the number of rows must match the height of the table.
I have attached a photo of the workspace variable of the table, only want to round certain rows as others have values which are unable to round
varnames={'Set Temp','duration','Start Temp','Time to Temp','Time to Steady','overshoot'};
for k=1:height(MasterTable)
for m=1:length(varnames)
varname=varnames{m};
MasterTable{k,varname}=mat2cell(round(cell2mat(MasterTable{k,varname})),3);
end
end
댓글 수: 2
dpb
2023년 2월 1일
'Set Temp' appears to be integer-valued already excepting you've got some locations that contain an array instead of a single value. Why is that; that'll screw up trying to do anything with the variable. Fix the data design first, then you can simply write
t.(varname)=round(t.(varname));
and be done.
답변 (2개)
Steven Lord
2023년 2월 2일
Using a sample table:
Temp = [37.3;39.1;42.3];
Pressure = [30.1;30.03;29.9];
WindSpeed = [13.4;6.5;7.3];
WindDirection = categorical({'NW';'N';'NW'});
T = table(Temp,Pressure,WindSpeed,WindDirection)
Let's round all the numeric variables.
T2 = varfun(@round, T, 'InputVariables', @isnumeric)
We can see which variables from T were used in the varfun computation.
areNumeric = varfun(@isnumeric, T, 'OutputFormat', 'uniform')
We could use those to overwrite the contents of T with T2. I'm going to make a backup copy of the original T for use in one more step.
T3 = T;
T(:, areNumeric) = T2
If you only want to round some of the values, specify InputVariables differently.
v = [true false true false];
T4 = varfun(@round, T3, 'InputVariables', v); % leave Pressure alone
T3(:, v) = T4
댓글 수: 0
Voss
2023년 2월 2일
If those columns that contain numeric values are cell arrays, as in
FW = ["EVT64"; "EVT64"; "EVT64"];
SetTemp = {[400;225]; [203;194]; 450};
Duration = {104.95; 264.15; 29.9833};
MasterTable = table(FW,SetTemp,Duration)
then you can modify your code as follows:
varnames = {'SetTemp','Duration'};
for k=1:height(MasterTable)
for m=1:length(varnames)
varname=varnames{m};
% MasterTable{k,varname}=mat2cell(round(cell2mat(MasterTable{k,varname})),3);
MasterTable.(varname){k} = round(MasterTable.(varname){k});
end
end
MasterTable
댓글 수: 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!