An efficient way to round decimal numbers up to the n-decimal in a cell array
9 views (last 30 days)
Show older comments
eIs there an efficient way to round decimal numbers up to the n-decimal in a cell array?
In the following example, I would like to round the decimal numbers up to n=2, i.e. to the second decimal:
a = [
{[ 0.235089379668094 0]}
{[0.0793405810870535 0]}
{[ 0.142843392632868 0]}
{[ 0.639081029130393 0]}
{[ 0.970756532033504 0]}
{[ 1 0]}]
My desired output would be the following one:
a = [
{[0.24 0]}
{[0.08 0]}
{[0.14 0]}
{[0.64 0]}
{[0.97 0]}
{[ 1 0]}]
0 Comments
Answers (2)
Jatin
on 8 Aug 2024
Edited: Jatin
on 8 Aug 2024
Yes, this can be efficiently done using the "cellfun" function in MATLAB.
"cellfun" applies a particular function to the contents of each cell of the cell array, In this case we can write a function to round decimal to two places and apply it to the cell array using this function.
Kindly refer the below example which rounds the contents of cell array to nth decimal places.
% Example cell array with decimal numbers
C = {1.234, 2.345, 3.456; 4.567, 5.678, 6.789};
% Number of decimal places to round up to
n = 2;
% Function to round up to the n-th decimal place
roundUpToNDecimals = @(x) ceil(x * 10^n) / 10^n;
% Apply the function to each element in the cell array
C = cellfun(roundUpToNDecimals, C);
disp(C);
If you would have a numeric array instead of a cell array this can be done efficiently using the element-wise operation like in the following example:
% Example numeric matrix with decimal numbers
M = [1.234, 2.345, 3.456; 4.567, 5.678, 6.789];
% Round up to the second decimal place
M = round(M,2);
disp(M);
You can refer the documentation of "cellfun" for more details:
Hope this helps
2 Comments
See Also
Categories
Find more on Data Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!