matlab 四捨五入 保留至指定小數

來源:互聯網
上載者:User
 
 

轉載出處:http://blog.csdn.net/yf210yf

Matlab取整函數有: fix, floor, ceil, round.取整函數在編程時有很大用處。 一、取整函數  1.向零取整(截尾取整) 

fix-向零取整(Round towards zero);

 >> fix(3.6)   

 ans =      3  2.向負無窮取整(不超過x 的最大整數-高斯取整) 

floor-向負無窮取整(Round towards minus infinity); 

>> floor(-3.6)   

ans =     -4  3.向正無窮取整(大於x 的最小整數) 

ceil-向正無窮取整(Round towards plus infinity); 

>> ceil(-3.6)    

ans =     -3  4.向最近整數取整,四捨五入(四捨五入取整) 

round-向最近整數取整,四捨五入(Round towards nearest integer); 

>> round(3.5) 

ans =      4    二、在小數點後某一位四捨五入,即保留幾位小數,也經常用到。  1.數值型 roundn—任意位位置四捨五入 

>>a=123.4567890; 

>>a=roundn(a,-4) 

a =   123.4568 

其中roundn函數功能如下:    

y = ROUNDN(x) rounds the input data x to the nearest hundredth.   %不指定n,精確到百分位 y = ROUNDN(x,n) rounds the input data x at the specified power    %精確到小數點後指定位元n  

2.符號型 

digits(4) 

vpa(....) 

必須說明:vpa命令不能識別整數與小數,只算總位元,因此對它來說小數整數無論哪個都佔一位,例如對9.3154保留兩位小數時就得寫成:

>>a=9.3154; 

>>digits(3) 

>>b=vpa(a) 

b=      9.32 

其中b為符號型變數;  3.字元型 

>>a=12.34567; 

>>b = sprintf('%8.2f',a) 

b =    12.35 其中b為字元型變數。 

  matlab文本輸出

兩個函數:disp

          fprintf 1、函數disp只帶一個變數,他可以是自負矩陣或數值矩陣,要輸出簡單的文字資訊,只需要用單引號將資訊括起來:

>>disp(‘my favorite color is red’);

或者

>>yourname=input(‘enter your name’,’s’);

>>disp([‘your name is’,youname]);

 

例如

>> yourname = input('enter your name ','s');

enter your name panrq

>> disp(['your name is ',yourname]);

your name is panrq

 

選擇帶數值變數值的文本資訊時,需要用函數num2str將數值變數的類型轉換字元型

>> x=98;

>> outstring = ['x = ',num2str(x)];

>> disp(outstring);

x = 98

>>  disp(['x = ',num2str(x)]);

x = 98

 

disp函數只能帶一個變數,表格中的各列需奧組合成一個矩陣,如下面的程式所示。

>> x=0:pi/5:pi;y=sin(x);

>> disp([x' y']);

         0         0

    0.6283    0.5878

    1.2566    0.9511

    1.8850    0.9511

    2.5133    0.5878

    3.1416    0.0000

 

Format命令

控制顯示模式,直到下一個format出現前,這條format命令一直有效。

>> x=1.23456789;

>> format short;disp(pi);

    3.1416

 

>> format long;disp(pi);

   3.141592653589793

 

>> format short e;disp(pi);

  3.1416e+000

 

>> format +;disp(pi);

+

 

>> format bank;disp(pi);

          3.14

  2、函數fprintf

fprintf(format);

fprintf(format,variables);

fprintf(fid,format,variables);

 

例如:

>> fprintf('i am concreten');

i am concrete

 

>> a=3;b='s';

>> fprintf('this is a %d and %s n',a,b);

this is a 3 and s

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.