matlab中disp函數的使用


 

 

  disp函數直接將內容輸出在Matlab命令窗口中,

   關鍵是看disp函數怎么把字符和數字在一起進行顯示。

matlab中disp()就是屏幕輸出函數,類似於c語言中的printf()函數

 

%%以下是一個通過給定兩點顯示直線方程的程序,

%%該程序需要給出兩個點的坐標,結果返回為y=kx+b的格式,且求得斜率

function [k,a1,b,type]=straight_line(A,B) % 輸入,A,B兩點坐標
V=B-A;
a=inf;
b=inf;
type='undefined';
if A==B
    'The two points are the same'
    return
end
if V(1)==0 && V(2)==0
    disp('Enter two distinct points next time')
    return
end
 
if V(1)==0
    type='vertical';
elseif V(2)==0
    type='horizontal';
else
    type='oblique';
    slope=atan2(V(2),V(1));
    s=inv([A(1) 1;B(1) 1])*[A(2) B(2)]';
    a=s(1);
    b=s(2);
end
 
switch type
    case 'vertical'
        disp('經過這兩個點的直線方程為::');
        disp(['x = ',num2str(A(1))]);
    case 'horizontal'
        disp(' 經過這兩個點的直線方程為:: ');
        disp(['y =',num2str(A(2))])  ;
    case 'oblique'
        disp(' 經過這兩個點的直線方程為:') ;
        disp(['y = ',num2str(a) ,' *x +',num2str(b)]);
        disp('斜率為:')
        k=num2str(a);%將符號數值化
end

 

disp(X)函數只有一個輸入,當你有多個字符串作為輸入時就會報錯。

例如:

disp('Alice is ' , num2str(12) , ' years old!' );

就會報錯--輸入參數過多。

但是將里邊的內容用中括號一括就成了一個字符串,

例如:

str=['Alice is ' num2str(12) ' years old!'];

disp(str);

上邊這句話也就等價於:

disp=(['Alice is ' num2str(12) ' years old!']);

這就是加中括號的原因,而不是因為num2str(),

因為disp(num2str(12));也是正確的,因為里邊就只有一個字符串。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM