intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Giới thiệu sơ lược ngôn ngữ matlab

Chia sẻ: Thanh Thanh | Ngày: | Loại File: PDF | Số trang:10

80
lượt xem
6
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Matlab là một ngôn ngữ thông dịch, cho phép thực hiện nhanh chóng các giải thuật, hiển thị dữ liệu (dưới dạng đồ thị 2D, 3D, hình ảnh và thậm chí chuỗi các hình ảnh) và thực hiện các giao tiếp đồ họa dễ dàng.

Chủ đề:
Lưu

Nội dung Text: Giới thiệu sơ lược ngôn ngữ matlab

  1. Gi i thi u sơ lư c v ngôn ng Matlab (Matrix Laboratory)
  2. Gi i thi u sơ lư c v ngôn ng Matlab Gi i thi u sơ lư c v ngôn ng Matlab Matlab là m t ngôn ng thông d ch, cho phép th c hi n nhanh chóng các gi i thu t, hi n th d li u (dư i d ng th 2D, 3D, hình nh và th m chí chu i các hình nh) và th c hi n các giao ti p h a d dàng. Tài li u này giúp làm quen nhanh chóng v i Matlab, khi n ngư i c c m th y thích thú trong vi c tìm hi u thêm. 1 Bt u làm quen 1.1 Chu n b Matlab s thông d ch các l nh ư c lưu trong t p tin có ph n m r ng .m (ví d toto.m) Ngư i dùng nên t o ra m t thư m c làm vi c (C:\Temp\ ch ng h n) lưu các chương trình c a mình, g i matlab và yêu c u nó th c hi n các l nh có trong t p tin chương trình toto.m 1.2 Ch y Matlab kh i ng Matlab, nh p chu t vào bi u tư ng Matlab n u b n dùng H H Windows ho c gõ matlab n u H H là Unix. Khung c a s làm vi c c a Matlab hi n ra v i d u nh c >>, cho phép ngư i dùng gõ vào các l nh mà nó s ư c th c hi n sau khi ngư i dùng gõ enter. Phía trên c a s là các thanh menu, cho phép ngư i dùng m t p tin, nh nghĩa m t s bi n làm vi c và nh t là truy xu t các t p tin giúp . Trư c khi làm vi c, nên ch ra thư m c làm vi c (nơi lưu tr các chương trình c a mình). Có 2 cách th c hi n i u này: 1. Ch n File/Set Path/Browse. thoát ra kh i c a s này, ch n File/Exit Path Brother. 2. T d u nh c c a Matlab, gõ các l nh: pwd, cd, dir. Các l nh này cho phép ngư i dùng di chuy n n thư m c làm vi c. 1.3 Ch y chương trình N u Matlab ang tích c c t i thư m c làm vi c mong mu n và trong thư m c ó có ch a chương trình dư i d ng t p tin .m, ngư i dùng ch c n gõ tên t p tin (không c n ph n m r ng) t d u nh c Matlab th c hi n các l nh lưu trong t p tin ó Ví d gõ >> toto Chú ý: Tên t p tin không ư c có các ký t lai (ví d các ký t d u, kho ng tr ng, ...). Matlab s - không nh n bi t ư c chính xác các tên t p tin có ch a các ký t này. Không nên dùng các tên quá ơn gi n. Ví d n u t p tin có tên max.m, khi gõ max t i - d u nh c, Matlab s không bi t ngư i dùng mu n th c hi n hàm max (l y s l n nh t c a m t ma tr n) ho c các l nh lưu tr trong max.m Cách ơn gi n nh t là dùng ký t u tiên c bi t cho tên t p tin c a riêng mình (ví d - k_toto.m) ho c dùng tên t p tin b ng ti ng Vi t ;-) Cơ b n v ngôn ng Matlab 2 2.1 Các ph n t u tiên L nh cơ b n u tiên c n th c hi n là clear. Nó cho phép xóa t t c các bi n trong b nh c a Matlab. Vi c gõ >> Var = 3; s gán cho bi n var ma tr n kích thư c 1x1 giá tr 3
  3. Gi i thi u sơ lư c v ngôn ng Matlab ư c hi n th sau phép N u không gõ d u ch m ph y (;) cu i l nh, giá tr c a var s gán. Ph n còn l i c a dòng l nh sau d u % s ư c coi như chú thích. k t n i dòng l nh hi n t i v i dòng l nh sau ó, gõ d u ... Ví d A= [ 1 2 3 ... 456] tương ương v i A= [123456] 2.2 X lý ma tr n 2.2.1 T ng quát % d u ph y (ho c kho ng cách) ngăn cách các c t >> A = [1, 2, 3; 4, 5, 6; 7, 8, 9] % d u ch m ph y (;) ngăn cách các hàng cho A= 1 2 3 4 5 6 7 8 9 % tăng các thành ph n c a vector t t 0 n 2.8 >> t = 0:0.2:2.8 % m i bư c 0.2 cho t = 0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0 2.2 2.4 2.6 2.8 % tính hàm sin cho các thành ph n c a t >> signal = sin(t) signal = 0 0.19 0.38 0.56 0.71 0.84 0.93 0.98 0.99 0.97 0.90 0.80 0.67 0.51 0.33 % giá tr ma tr n có d ng ph c >> ZZ = [1 2 5] +i*[8 6 4] ZZ = 1.0 + 8.0i 2.0 + 6.0i 5.0 + 4.0i Dùng l nh size n u mu n bi t kích thư c m t ma tr n >> size(ZZ) s cho % m t dòng và 3 c t ans = 1 3 2.2.2 L y các giá tr c a m t ma tr n A(i, j) bi u di n ph n t dòng i c t j c a ma tr n A >> B = A(2, 3) s cho B=6 A(:,j) bi u di n c t th j >> C = A(:,2) s cho C= 2 5 8 A(i:k,:) bi u di n các dòng t i nk >> D = A(1:2,:) cho D= 123 456 A(i:k,j:l) bi u di n ma tr n con >> E = A(2:3,2:3) cho E= 56 89 2.2.3 Xây d ng ma tr n có kích thư c tăng D u ph y phân cách các c t và d u ch m ph y phân cách các hàng. >> F = [A C] s cho F= 1232
  4. Gi i thi u sơ lư c v ngôn ng Matlab 4565 7898 >> G = [A; A(2,:)] cho G= 12 3 45 6 78 9 45 6 % ma tr n r ng >> Z = [] Có th b m t dòng c a ma tr n b ng cách sau >> A(:,2) = [] s cho A= 13 46 79 2.3 Nh p/Xu t 2.3.1 Nh p/Xu t màn hình % in ra chu i "Nhap gia tri ban dau: " trên >> x = input(' Nhap gia tri ban dau: '); % màn hình, giá tr nh p vào s gán cho x 2.3.2 Nh p/Xu t t p tin Nh p/xu t riêng c a Matlab • D ng nh phân % lưu A, B, C trong t p tin file1.mat >> save file1 A B C % n p A, B, C trong b nh b i các giá tr >> load file1 % lưu trong t p tin file1.mat • D ng văn b n Ch lưu tr m t ma tr n trong m t t p tin. % lưu các giá tr c a A trong t p tin >> save file2.dat A -ascii % file2.dat dư i d ng văn b n % l y các giá tr lưu tr trong file2.dat và >> load file2.dat % gán nó cho bi n file2 Nh p/xu t chu n c các giá tr lưu tr trong t p tin nh phân, c n ph i dùng các l nh: >> fidin = fopen('file3.dat','r'); % m t p tin file3.dat trong thư m c hi n hành % c và gán handle tr v cho fidin c 2000 giá tr ư c lưu như unsigned char >> data = fread(fidin, 2000, 'uchar');% % và gán nó cho data % óng t p tin ư c tr b i fidin (file3.dat) >> fclose(fidin); ghi các giá tr trong m t t p tin nh phân có kh năng c b i các công c ph n m m khác, ta c n dùng các l nh: >> fidout = fopen('file4.dat','w'); % m t p tin file4.dat ghi (d ng nh phân) % ghi các giá tr data dư ng d ng unsigned char >> fwrite(fidout, data, 'uchar'); % óng t p tin >> fclose(fidout); 2.4 Hi n th ha % v d ng sóng signal >> plot(signal) % hi n th h a 3D các giá tr ma tr n >> mesh(A) % hi n th chu i trên hình h a >> title('Hinh 1') % phân chia màn hình thành ma tr n d1xd2 >> subplot(d1, d2, d) % và v th trong vùng th d 2.5 G l i (debug)
  5. Gi i thi u sơ lư c v ngôn ng Matlab Dùng l nh whos bi t danh sách và kích thư c các bi n trong b nh hi n t i. ng ng t m th i trong m t danh sách các l nh, dùng l nh pause. Chương trình s ư c th c hi n ti p khi có m t phím b t kỳ ư c gõ. có th tích c c trong c a s môi trư ng Matlab (t c ngư i dùng có th gõ l nh) trong khi chương trình ang ư c th c thi, dùng l nh keyboard trong chương trình. Quá trình th c hi n l nh trong chương trình b ng t t m th i, cho phép ngư i dùng hi n th giá tr các bi n. Khi chương trình ti p t c ư c th c thi, gõ enter trong c a s ó d u nh c s tr thành K>>. l nh. d ng chương trình, nh n Ctrl-C. 3 Ví d chương trình zap.m clear % Xóa t t c d li u trong b nh %------------------ T o các tín hi u ---------------------------------------% FeSparc=8192; % T n s l y m u dùng trên các tr m làm vi c Sun (Sparc) TeSparc=1/FeSparc; FreqSig=input('Tan so tin hieu ?'); % t câu h i và gán câu tr l i cho FreqSig % (th 4096 = FeSparc/2) NbEch=4096 % s m u ư c hi n th trong c a s làm vi c Matlab (không có ;) t=0:TeSparc:(NbEch-1)*TeSparc; % t o m t vector Signal=sin(2*pi*FreqSig*t); % t o ra vector Signal Coef=0.1; Bruit=Coef*(2*rand(1,NbEch)-1); % rand: t o ma tr n mà các thành ph n có giá tr ng u nhiên SignalBruit=Signal+Bruit; %------------------ X lý chu i các ký t ----------------------------------% FreqString=num2str(FreqSig); % chuy n m t s thành chu i các ký t CoefString=num2str(Coef); chaine2=['Nhieu trang tai ',CoefString,'%']% N i chu i %Minh h a vi c ng t l nh b ng ... chaine1=['Tin hieu: hinh sin voi tan so ',FreqString,... ' Hertz'] %------------------ Hi n th h a ----------------------------------------% subplot(2,2,1); % Ph n chia c a s h a thành ma tr n 2x2, và ch n vùng 1 plot(Signal); % Phác h a vector Signal title('Signal'); % T a c a h a hi n hành sound(Signal,FeSparc); % Phát âm thanh c a vector Signal, ư c l y m u t i t n s FeSparc subplot(2,2,2); plot(Bruit); title('Nhieu'); disp('Go phim bat ky de tiep tuc …'); pause sound(Bruit,FeSparc); subplot(2,2,3); plot(SignalBruit); title('Tin hieu + nhieu'); disp('Go phim bat ky de tiep tuc …'); pause sound(SignalBruit,FeSparc); subplot(2,2,4); text('units','normalized','Position',... % Hi n th chu i "chaine2" [0,0.75],'String',chaine2,'Color','r'); text('units','normalized','Position',[0,0.25],'String',chaine1,'Color','g'); axis off % Xóa tr c t a trên hình v hi n t i clear desiderata=input('Ban muon nghe mot tap tin am thanh ?','s'); delete(gcf) % óng c a s h a hi n t i if (desiderata=='yes') FichierIn='_rvmaitr.wav'; [Data,freq]=wavread(FichierIn);% N p t n s và tín hi u trong t p tin "Gong.mat" whos % Hi n th d li u m i trong b nh
  6. Gi i thi u sơ lư c v ngôn ng Matlab plot(Data); Data=-0.5+Data/max(Data); sound(Data,freq); end % c t p tin sys1.mat ư c lưu tr dư i d ng văn b n fid=fopen('sys1.mat','r'); [h,count]=fscanf(fid,'%f'); status =fclose(fid); plot(h); % X lý hình nh clear Data=imread('im.bmp','bmp'); % Lưu hình trong ma tr n 3D coucou=imfinfo('im.bmp','bmp') % L y thông tin c a hình nh image(Data) % Xem nh tr ng en (B&W) DataYY= 0.299*double(Data(:,:,1))+ ... 0.587*double(Data(:,:,2))+ ... 0.114*double(Data(:,:,3)); % Ch l y các giá tr nguyên % Các i m nh ch y t 0 n 255 DataYY=floor(DataYY); % T o m t palette xám có tr t 0 n 1 GrayMap=(0:255)/255; GrayMap=[GrayMap',GrayMap',GrayMap']; disp('Go nhe mot phim'); pause % Kh i t o palette m c nh colormap(GrayMap) % Ch s ma tr n i t 0 n 255 ư c i kèm nh ng ch s c a palette t 0 n 1 (255) image(DataYY) % L nh sau b t bu c (xem help imwrite) DataYY=uint8(DataYY); lưu hình trên ĩa c ng: % % Chú ý: r ng c a hình ph i là b i s c a 4 (pb windows) imwrite(DataYY,GrayMap,'new_ima.bmp','bmp') 4 Danh sách các l nh Sau ây là danh sách các l nh thư ng dùng. ng ng i t n 5 phút xem qua, nó s giúp b n ti t ki m r t nhi u th i gian sau này: nó s giúp b n tránh vi c vi t l i các o n chương trình vô ích. clc Clear command window echo Echo M-files during execution General Purpose Commands format Control the output display format Managing Commands and Functions help Online help for MATLAB functions and M-files Working with Files and the Operating helpdesk Display Help Desk page in Web browser, Environment giving access to extensive help cd Change working directory help for all commands copyfile Copy file delete Delete files and graphics objects Managing Variables and the Workspace dir Directory listing clear Remove items from memory ls List directory on UNIX disp Display text or array mkdir Make directory length Length of vector pwd Display current directory load Retrieve variables from disk ! Execute operating system command pack Consolidate workspace memory save Save workspace variables on disk Operators and Special Characters saveas Save figure or model using specified format + Plus size Array dimensions - Minus who, whos List directory of variables in memory * Matrix multiplication workspace Display the Workspace Browser, a GUI for .* Array multiplication managing the workspace. ^ Matrix power .^ Array power Controlling the Command Window
  7. Gi i thi u sơ lư c v ngôn ng Matlab kron Kronecker tensor product.1-4 try Begin try block warning Display warning message \ Backslash or left division while Repeat statements an indefinite number of times / Slash or right division ./ and .\ Array division, right and left Interactive Input : Colon input Request user input ( ) Parentheses keyboard Invoke the keyboard in an M-file [ ] Brackets menu Generate a menu of choices for user input {} Curly braces pause Halt execution temporarily . Decimal point ... Continuation Object-Oriented Programming , Comma double Convert to double precision ; Semicolon int8, int16, int32 Convert to signed integer % Comment uint8, uint16, uint32 Convert to unsigned integer ! Exclamation point ' Transpose and quote Elementary Matrices and Matrix .' Nonconjugated transpose = Assignment Manipulation == Equality Elementary Matrices and Arrays < > Relational operators eye Identity matrix & Logical AND ones Create an array of all ones | Logical OR rand Uniformly distributed random numbers and arrays ~ Logical NOT randn Normally distributed random numbers and arrays xor Logical EXCLUSIVE OR zeros Create an array of all zeros : (colon) Regularly spaced vector Logical Functions all Test to determine if all elements are nonzero Special Variables and Constants any Test for any nonzeros ans The most recent answer exist Check if a variable or file exists eps Floating-point relative accuracy find Find indices and values of nonzero elements flops Count floating-point operations is* Detect state i Imaginary unit. isa Detect an object of a given class Inf Infinity logical Convert numeric values to logical j Imaginary unit NaN Not-a-Number Language Constructs and Debugging nargin, nargout Number of function arguments MATLAB as a Programming Language pi Ratio of a circle's circumference to its diameter,p eval Interpret strings containing MATLAB expressions varargin, varargout Pass or return variable numbers of evalc Evaluate MATLAB expression with capture. arguments evalin Evaluate expression in workspace feval Function evaluation Time and Dates function Function M-files calendar Calendar global Define global variables clock Current time as a date vector nargchk Check number of input arguments cputime Elapsed CPU time date Current date string Control Flow etime Elapsed time break Terminate execution of for loop or while loop now Current date and time case Case switch tic, toc Stopwatch timer catch Begin catch block else Conditionally execute statements Matrix Manipulation elseif Conditionally execute statements cat Concatenate arrays end Terminate for, while, switch, try, and if statements diag Diagonal matrices and diagonals of a matrix or indicate last index fliplr Flip matrices left-right for Repeat statements a specific number of times flipud Flip matrices up-down if Conditionally execute statements repmat Replicate and tile an array otherwise Default part of switch statement reshape Reshape array return Return to the invoking function rot90 Rotate matrix 90 degrees switch Switch among several cases based on expression
  8. Gi i thi u sơ lư c v ngôn ng Matlab tril Lower triangular part of a matrix max Maximum elements of an array mean Average or mean value of arrays triu Upper triangular part of a matrix median Median value of arrays : (colon) Index into array, rearrange array. min Minimum elements of an array perms All possible permutations Elementary Math Functions prod Product of array elements abs Absolute value and complex magnitude sort Sort elements in ascending order acos, acosh Inverse cosine and inverse hyperbolic sortrows Sort rows in ascending order cosine std Standard deviation acot, acoth Inverse cotangent and inverse hyperbolic sum Sum of array elements cotangent var Variance acsc, acsch Inverse cosecant and inverse hyperbolic voronoi Voronoi diagram cosecant angle Phase angle Finite Differences asec, asech Inverse secant and inverse hyperbolic del2 Discrete Laplacian secant diff Differences and approximate derivatives. asin, asinh Inverse sine and inverse hyperbolic sine gradient Numerical gradient atan, atanh Inverse tangent and inverse hyperbolic tangent Correlation atan2 Four-quadrant inverse tangent corrcoef Correlation coefficients ceil Round toward infinity cov Covariance matrix complex Construct complex data from real and imaginary components Filtering and Convolution conj Complex conjugate conv Convolution and polynomial multiplication cos, cosh Cosine and hyperbolic cosine conv2 Two-dimensional convolution cot, coth Cotangent and hyperbolic cotangent deconv Deconvolution and polynomial division csc, csch Cosecant and hyperbolic cosecant filter Filter data with an infinite impulse response (IIR) exp Exponential or finite impulse response (FIR) filter fix Round towards zero filter2 Two-dimensional digital filtering floor Round towards minus infinity gcd Greatest common divisor Fourier Transforms imag Imaginary part of a complex number abs Absolute value and complex magnitude lcm Least common multiple angle Phase angle log Natural logarithm fft One-dimensional fast Fourier transform log2 Base 2 logarithm and dissect floating-point fft2 Two-dimensional fast Fourier transform numbers into exponent and mantissa ifft Inverse one-dimensional fast Fourier transform log10 Common (base 10) logarithm ifft2 Inverse two-dimensional fast Fourier transform mod Modulus (signed remainder after division) unwrap Correct phase angles nchoosek Binomial coefficient or all combinations. real Real part of complex number Polynomial and Interpolation rem Remainder after division round Round to nearest integer Functions sec, sech Secant and hyperbolic secant Polynomials sign Signum function conv Convolution and polynomial multiplication sin, sinh Sine and hyperbolic sine deconv Deconvolution and polynomial division sqrt Square root tan, tanh Tangent and hyperbolic tangent Sound Processing Functions General Sound Functions Eigenvalues and Singular Values sound Convert vector into sound eig Eigenvalues and eigenvectors gsvd Generalized singular value decomposition SPARCstation-Specific Sound Functions svd Singular value decomposition auread Read NeXT/SUN (.au) sound file auwrite Write NeXT/SUN (.au) sound file Data Analysis and Fourier Transform Functions .WAV Sound Functions wavread Read Microsoft WAVE (.wav) sound file Basic Operations
  9. Gi i thi u sơ lư c v ngôn ng Matlab wavwrite Write Microsoft WAVE (.wav) sound file. reshape Reshape array Plotting and Data Visualization Character String Functions Basic Plots and Graphs General bar Vertical bar chart abs Absolute value and complex magnitude barh Horizontal bar chart eval Interpret strings containing MATLAB expressions hist Plot histograms real Real part of complex number hold Hold current graph strings MATLAB string handling loglog Plot using log-log scales plot Plot vectors or matrices. String to Number Conversion semilogx Semi-log scale plot char Create character array (string) semilogy Semi-log scale plot int2str Integer to string conversion subplot Create axes in tiled positions mat2str Convert a matrix into a string num2str Number to string conversion Three-Dimensional Plotting sprintf Write formatted data to a string plot3 Plot lines and points in 3-D space sscanf Read string under format control str2double Convert string to double-precision value Plot Annotation and Grids str2num String to number conversion grid Grid lines for 2-D and 3-D plots gtext Place text on a 2-D graph using a mouse Low-Level File I/O Functions legend Graph legend for lines and patches File Opening and Closing plotyy Plot graphs with Y tick labels on the left and fclose Close one or more open files right fopen Open a file or obtain information about open files title Titles for 2-D and 3-D plots xlabel X-axis labels for 2-D and 3-D plots Unformatted I/O ylabel Y-axis labels for 2-D and 3-D plots fread Read binary data from file zlabel Z-axis labels for 3-D plots fwrite Write binary data to a file Surface, Mesh, and Contour Plots Formatted I/O contour Contour (level curves) plot fgetl Return the next line of a file as a string without meshc Combination mesh/contourplot line terminator(s) mesh 3-D mesh with reference plane fgets Return the next line of a file as a string with line peaks A sample function of two variables terminator(s) surf 3-D shaded surface graph fprintf Write formatted data to file surface Create surface low-level objects fscanf Read formatted data from file surfc Combination surf/contourplot surfl 3-D shaded surface with lighting File Positioning feof Test for end-of-file Domain Generation ferror Query MATLAB about errors in file input or griddata Data gridding and surface fitting output meshgrid Generation of X and Y arrays for 3-D plots frewind Rewind an open file fseek Set file position indicator Color Operations ftell Get file position indicator colormap Set the color look-up table hsv2rgb Hue-saturation-value to RGB conversion String Conversion rgb2hsv RGB to HSVconversion sprintf Write formatted data to a string rgbplot Plot color map sscanf Read string under format control Colormaps Specialized File I/O bone Gray-scale with a tinge of blue color map imfinfo Return information about a graphics file contrast Gray color map to enhance image contrast imread Read image from graphics file. cool Shades of cyan and magenta color map imwrite Write an image to a graphics file copper Linear copper-tone color map textread Read formatted data from text file flag Alternating red, white, blue, and black color map gray Linear gray-scale color map Multidimensional Array Functions hot Black-red-yellow-white color map
  10. Gi i thi u sơ lư c v ngôn ng Matlab hsv Hue-saturation-value (HSV) color map spring Shades of magenta and yellow color map Handle Graphics, Figure Windows summer Shades of green and yellow colormap capture Screen capture of the current figure winter Shades of blue and green color map clc Clear figure window clf Clear figure clg Clear figure (graph window) Printing print Print graph or save graph to file close Close specified window printopt Configure local printer defaults gcf Get current figure handle saveas Save figure to graphic file newplot Graphics M-file preamble for NextPlot property refresh Refresh figure Handle Graphics, Object Creation saveas Save figure or model to desired output format axes Create Axes object figure Create Figure (graph) windows image Create Image (2-D matrix) Handle Graphics, Axes line Create Line object (3-D polylines) axis Plot axis scaling and appearance cla Clear Axes text Create Text object (character strings) gca Get current Axes handle Interactive User Input ginput Graphical input from a mouse or cursor zoom Zoom in and out on a 2-D plot Region of Interest drawnow Complete any pending drawing
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2