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

8 visualizzazioni (ultimi 30 giorni)
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]}]

Risposte (2)

Jatin
Jatin il 8 Ago 2024
Modificato: Jatin il 8 Ago 2024
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 il 8 Ago 2024
Modificato: Sim il 8 Ago 2024
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 Commenti
Stephen23
Stephen23 il 8 Ago 2024
"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 il 8 Ago 2024
Ahhh, in that way..! I did not understand before, it is now clear! Thanks a lot :-)

Accedi per commentare.

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by