How to round numbers in tables?

조회 수: 70 (최근 30일)
Hao Tang
Hao Tang 2018년 2월 22일
댓글: the cyclist 2021년 10월 2일
How can I round a number in a matlab table after it does its calculation? I have a cell that calculates the value to be 0.009999998 but I want it to read 0.01. I tried using format short g in the script but that didn't work.

답변 (3개)

the cyclist
the cyclist 2018년 2월 22일
편집: the cyclist 2018년 2월 22일
Use the round function.
You could have discovered this for yourself by typing
docsearch round
in the MATLAB command window, or typing
round matlab
into Google.
Note that there is a difference between the value that is calculated/stored, and how it is displayed. The format command is about the display.
  댓글 수: 2
Bill Tubbs
Bill Tubbs 2021년 10월 2일
I found the round function doesn't work with tables:
>> round(table(randn(3,4)), 3)
Error using round
First argument must be a numeric, logical, or char array.
So this answer was not helpful.
the cyclist
the cyclist 2021년 10월 2일
See my comment on your "answer" below.

댓글을 달려면 로그인하십시오.


Star Strider
Star Strider 2018년 2월 22일
If you do not have the R2015a (I believe that is the correct release) that introduced the new round function, this anonymous function emulates it:
roundn = @(x,n) round(x .* 10.^n)./10.^n; % Round ‘x’ To ‘n’ Digits, Emulates Latest ‘round’ Function
x = 0.009999998;
xr = roundn(x,2)
xr =
0.01
  댓글 수: 4
Star Strider
Star Strider 2018년 2월 23일
@Guillaume — Thank you!
Lance Yarbrough
Lance Yarbrough 2019년 4월 14일
편집: Lance Yarbrough 2019년 4월 14일
THANK YOU!! Looking for this answer forr most of the DAY.

댓글을 달려면 로그인하십시오.


Bill Tubbs
Bill Tubbs 2021년 10월 2일
Is here a way to use the round function with tables?
Simply using round(my_table, 3) does not work:
t = array2table(randn(3, 4), 'VariableNames', {'A', 'B', 'C', 'D'}, ...
'RowNames', {'1', '2', '3'});
round(t, 3)
Output:
Error using round
First argument must be a numeric, logical, or char array.
I found this solution but it's quite convoluted:
t2 = t; t2{:, :} = round(t.Variables, 3)
Output:
t2 =
3×4 table
A B C D
______ ______ ______ ______
1 0.722 0.187 -0.439 -0.888
2 2.585 -0.082 -1.795 0.1
3 -0.667 -1.933 0.84 -0.545
Surely there is a better way...
  댓글 수: 3
Bill Tubbs
Bill Tubbs 2021년 10월 2일
Thanks but this doesn't preserve the row and column names, and possibly other attributes of the table.
I found the same question answered here by Steven Lord STAFF MVP.
the cyclist
the cyclist 2021년 10월 2일
OK. I can't tell from this comment whether you ended up with a solution that works for you.
If not, you might want to start a new question with your specific needs, rather than commenting and "answering" on an older question. You'll typically get more eyes on it if you do.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by