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

8 ビュー (過去 30 日間)
Sim
Sim 2024 年 8 月 8 日
コメント済み: Jatin 2024 年 8 月 8 日
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
  2 件のコメント
Sim
Sim 2024 年 8 月 8 日
Thanks @Jatin Singh, very kind, it is the same I wrote :-)
Jatin
Jatin 2024 年 8 月 8 日
Yes, you figured it out pretty well.

サインインしてコメントする。


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>
Sim
Sim 2024 年 8 月 8 日
Ahhh, in that way..! I did not understand before, it is now clear! Thanks a lot :-)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by