Round all values in table
56 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have a table with calculated values. Now I want to round all values to 2 decimals. How can I do that in once for the whole table?
0 commentaires
Réponses (2)
Scott MacKenzie
le 25 Oct 2021
Modifié(e) : Scott MacKenzie
le 25 Oct 2021
I think this achieves what you are after:
% test data
T1 = array2table(rand(5))
% rounded to 2 decimal places
T2 = array2table(round(T1{:,:},2))
0 commentaires
Andrew Sandeman
le 14 Juil 2025 à 11:46
Another solution using varfun()
% test data
T = array2table(rand(5))
% round data in table to 2 d.p.
varfun(@(x)round(x,2), T)
The only difference is the variable names.
4 commentaires
Walter Roberson
le 14 Juil 2025 à 23:32
That's an interesting use of table assignment.
Needs more work if there could be multiple output variables.
t = table(rand(5,1), rand(5,1), repelem("a",5,1))
outvars = t.Properties.VariableNames(varfun(@isnumeric,t,OutputFormat="uniform"))
t(:,outvars) = varfun(@(x)round(x,2), t, InputVariables=outvars)
Andrew Sandeman
le 15 Juil 2025 à 0:12
And here it is wrapped up in a function.
Awesome! I feel like with some documentation it might be worth putting on the file exchange?
t = table(rand(5,1), rand(5,1), repelem("a",5,1))
conditionalVarfun(t, @isnumeric, @(x)round(x,2))
%% functions
function t = conditionalVarfun(t, fh_condition, fh_operation)
% t (table)
% fh_condition e.g. @isnumeric
% fh_operation e.g. @(x)round(x,2)
p = inputParser;
p.addRequired("t", @istable)
p.addRequired("fh_condition", @isfunctionhandle)
p.addRequired("fh_operation", @isfunctionhandle)
p.parse(t, fh_condition, fh_operation)
t = p.Results.("t");
fh_condition = p.Results.("fh_condition");
fh_operation = p.Results.("fh_operation");
outvars = t.Properties.VariableNames(varfun(fh_condition,t,OutputFormat="uniform"));
t(:,outvars) = varfun(fh_operation, t, InputVariables=outvars);
end
function bool = isfunctionhandle(x)
bool = isa(x, 'function_handle');
end
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!