How to round values of table with mixed types?
Afficher commentaires plus anciens
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 commentaires
dpb
le 1 Fév 2023
'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.
Nicholas Kavouris
le 2 Fév 2023
Réponses (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
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
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!