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

8 次查看(过去 30 天)
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]}]

回答(2 个)

Jatin
Jatin 2024-8-8
编辑:Jatin 2024-8-8
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

Sim
Sim 2024-8-8
编辑:Sim 2024-8-8
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)
  4 个评论
Stephen23
Stephen23 2024-8-8
"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>

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Types 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by