# An efficient way to round decimal numbers up to the n-decimal in a cell array

8 views (last 30 days)
Sim on 8 Aug 2024 at 9:56
Commented: Jatin Singh on 8 Aug 2024 at 11:57
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]}]

Jatin Singh on 8 Aug 2024 at 10:16
Edited: Jatin Singh on 8 Aug 2024 at 10:33
Hi @Sim,
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 CommentsShow NoneHide None
Sim on 8 Aug 2024 at 10:44
Thanks @Jatin Singh, very kind, it is the same I wrote :-)
Jatin Singh on 8 Aug 2024 at 11:57
Yes, you figured it out pretty well.

Sim on 8 Aug 2024 at 10:03
Edited: Sim on 8 Aug 2024 at 10:11
maybe I found it... (?)
a = [
{[ 0.235089379668094 0]}
{[0.0793405810870535 0]}
{[ 0.142843392632868 0]}
{[ 0.639081029130393 0]}
{[ 0.970756532033504 0]}
{[ 1 0]}];
cellfun(@(x)round(x,2),a,'UniformOutput',false)
Stephen23 on 8 Aug 2024 at 10:50
"How to do it"
m = [0.235089379668094,0; 0.0793405810870535,0; 0.142843392632868,0; 0.639081029130393,0; 0.970756532033504,0;1,0]
m = 6x2
0.2351 0 0.0793 0 0.1428 0 0.6391 0 0.9708 0 1.0000 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
m = round(m,2)
m = 6x2
0.2400 0 0.0800 0 0.1400 0 0.6400 0 0.9700 0 1.0000 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Sim on 8 Aug 2024 at 11:00
Ahhh, in that way..! I did not understand before, it is now clear! Thanks a lot :-)