matlab初學之strcat、num2str


文章出處:

http://blog.sina.com.cn/s/blog_6fb8aa0d01019id5.html

http://wenda.so.com/q/1439143662729624

http://blog.sina.com.cn/s/blog_412888260100g73b.html

 

1.strcat

連接字符串的函數

一、例:

a = 'hello '
b = 'goodbye'
strcat(a, b)
ans =
hellogoodbye

 

二、注意:

①在同一行輸出

②strcat聯接的兩個string都是直接連在一起的,中間不能加入空格。不過可以在定義字符時,在字符中加空格

 

三、tictoc

Matlab連接字符串用strcat好,還是用 [ ] 好?

clear all;
close all
tic;
for i = 1:100
['hello', num2str(i)];
end
t1 = toc;

close all;
clear all;
t = tic;
for i = 1:100
strcat('hello', num2st(i));
end
t2  = toc;

>>

t1 = 0.0229
t2 = 0.0555

**********************************由此可見,[ ] 運行的效率要比strcat高一些。因為strcat 內部需要做一些預處理和其他的數據類型,比如cell。

 

 

 

2.num2str

函數功能:
把數值轉換成字符串, 轉換后可以使用fprintf或disp函數進行輸出。在matlab命令窗口中鍵入doc num2str或help num2str即可獲得該函數的幫助信息。
  
語法格式:
  str = num2str(A)
  把數組A中的數轉換成字符串表示形式。
  str = num2str(A, precision)
  把數組A轉換成字符串形式表示,precision表示精度, 比如precision為3表示保留最多3位有效數字, 例如0.5345轉換后為0.534,1.2345轉換后為1.23。即從左邊第一個不為0的數開始保留3個數值。
  str = num2str(A, format)
  按format指定格式進行格式化轉換,通常'%11.4g'是默認的。

相關函數:
mat2str, int2str, str2num, sprintf, fprintf

應用舉例:
  >> A = [1, 2, 3];
  >> B = num2str(A);
  >> fprintf('%s', B)
  1 2 3>>
  >> C = [1.564, 0.12345];
  >> D = num2str(C, 3)
  D =
  1.56 0.123
  >> D = int32(1)
  D =
  1
  >> num2str(D, '%.6f')
  ans =
  1.000000

3.num2str應用

在求導數,積分,方程的過程中,難免會遇到一些參數要隨着情況有點變化,這時,你就需要能夠動態的表示出你的表達式,Num2str函數是一個相當有用的函數,一般配合[]連接符使用,下面將我接觸到的一些用法寫出來。

1 )用於求導數的表達式,函數X^2 – y^p + y^t,pt為數值,可以跟隨程序的不同被賦予不同的值。 Diff([‘x^2 – y^’ num2str(p) ‘+y^’ num2str(t), x])

2) 用於求解積分用法同上,把被積函數表示出來就可以了。 int([‘x^2 – y^’ num2str(p) ‘+y^’ num2str(t), x, a,b])

3 )用於求解方程或微分方程 Solve([‘x^2 – x^’ num2str(p) ‘+x^’ num2str(t)],x) Dsolve([‘Dx^2 – x^’ num2str(p) ‘+x^’ num2str(t)], x)

4) 如果你要運行一些大的算法,涉及到了循環,你不防試試下面的方法,提示程序的進度。這個是我在做Monte Carlo時的一個收獲。 Plot(...)任意的繪圖, Text(x, y , ['Monte Carlo Number=' num2str(mc) '/' num2str(NMc)])將這個語句寫在循環體的內部。

5 )在保存圖像的時候用到動態的給文件起名的時候,也可以用這個語句。文件名[‘file’ num2str(i) ‘.bmp’]i為循環計數名。

 

實例:

obsfile = strcat(obspath,num2str(msta(ista)),'A.txt');

 


免責聲明!

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



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