help help funkcja_o_której_chcemy_sie_dowiedzieć
Proszę poszukać na różne sposoby informacji o funkcji
plot
Polecenie
help matlab/generalprodukuje następujący wydruk (bardziej użyteczne komendy zostały wytłuszczone)
General purpose commands. MATLAB Version 6.5 (R13) 20-Jun-2002 General information helpbrowser - Bring up the help browser. doc - Complete on-line help, displayed in the help browser.
help - M-file help, displayed at the command line.
helpwin - M-file help, displayed in the help browser. lookfor - Search all M-files for keyword. syntax - Help on MATLAB command syntax. support - Open MathWorks Technical Support Web Page. demo - Run demonstrations.
ver - MATLAB, SIMULINK, and toolbox version information.
version - MATLAB version information. whatsnew - Access Release Notes. Managing the workspace.
workspace - Display Workspace Browser, a GUI for managing the workspace. pack - Consolidate workspace memory.
Managing commands and functions. what - List MATLAB-specific files in directory.
type - List M-file.
edit - Edit M-file. open - Open files by extension. which - Locate functions and files. pcode - Create pre-parsed pseudo-code file (P-file). inmem - List functions in memory. mex - Compile MEX-function. Managing the search path path - Get/set search path. addpath - Add directory to search path. rmpath - Remove directory from search path. pathtool - Modify search path. rehash - Refresh function and file system caches. import - Import Java packages into the current scope. Controlling the command window. echo - Echo commands in M-files. more - Control paged output in command window. diary - Save text of MATLAB session. format - Set output format. beep - Produce beep sound. Operating system commands
cd - Change current working directory.
copyfile - Copy a file or directory. movefile - Move a file or directory. delete - Delete file. pwd - Show (print) current working directory. dir - List directory. fileattrib - Get or set attributes of files and directories. isdir - True if argument is a directory. mkdir - Make directory. rmdir - Remove directory. getenv - Get environment variable. ! - Execute operating system command (see PUNCT). dos - Execute DOS command and return result. unix - Execute UNIX command and return result. system - Execute system command and return result. perl - Execute Perl command and return result. web - Open Web browser on site or files. computer - Computer type. isunix - True for the UNIX version of MATLAB. ispc - True for the PC (Windows) version of MATLAB. Debugging M-files. debug - List debugging commands. dbstop - Set breakpoint. dbclear - Remove breakpoint. dbcont - Continue execution. dbdown - Change local workspace context. dbstack - Display function call stack. dbstatus - List all breakpoints. dbstep - Execute one or more lines. dbtype - List M-file with line numbers. dbup - Change local workspace context. dbquit - Quit debug mode. dbmex - Debug MEX-files (UNIX only). Profiling M-files. profile - Profile function execution time. profreport - Generate profile report. Tools to locate dependent functions of an M-file. depfun - Locate dependent functions of an m-file. depdir - Locate dependent directories of an m-file. inmem - List functions in memory.
a=1; whos
Spis podstawowych operacji na macierzach otrzymamy wpisując
help matlab/elmat
Najczęściej przeze mnie używane to:
linspace - Linearly spaced vector. logspace - Logarithmically spaced vector. meshgrid - X and Y arrays for 3-D plots. Basic array information.
ndims - Number of dimensions. disp - Display matrix or text. isempty - True for empty array. Matrix manipulation. cat - Concatenate arrays. reshape - Change size. diag - Diagonal matrices and diagonals of matrix. fliplr - Flip matrix in left/right direction. flipud - Flip matrix in up/down direction. flipdim - Flip matrix along specified dimension. rot90 - Rotate matrix 90 degrees.
Special variables and constants. ans - Most recent answer. eps - Floating point relative accuracy. pi - 3.1415926535897.... i, j - Imaginary unit.
Macierze możemy wpisywać "z palca":
>> A=[1 2 3 4; 5 6 7 8; 8 9 1 2]; >> A A = 1 2 3 4 5 6 7 8 8 9 1 2 >> disp(A) 1 2 3 4 5 6 7 8 8 9 1 2
Wczytywać je z plików lub uzyskiwać w wyniku działania funkcji.
Większość operacji działa na macierzach w sposób intuicyjny:
Transpozycja:
>> A' ans = 1 5 8 2 6 9 3 7 1 4 8 2Sumowanie
>> sum(A) ans = 14 17 11 14
>> sum(A') ans = 10 26 20Możemy też jawnie podać wymiar po którym dana operacja ma być wykonana
>> sum(A,2) ans = 10 26 20
Działają też zwykłe operatory
>> B=[1 2;3 4] B = 1 2 3 4 >> B+B ans = 2 4 6 8 >> B-B ans = 0 0 0 0Operatory
>> B/B ans = 1 0 0 1 >> B*B ans = 7 10 15 22Operatory
>> B./B ans = 1 1 1 1 >> B.*B ans = 1 4 9 16
Do elementu macierzy dostajemy się tak:
>> B(1,2) ans = 2Teraz zmieniamy jego wartość:
>> B(1,2)=4; >> B B = 1 4 3 4 >>Zwróćmy uwagę, że przy modyfikowaniu elementów macierzy jej rozmiar dostosowuje się automatycznie i może się zmienić!:
>> B(1,3)=4; >> B B = 1 4 4 3 4 0
Kontrola zakresu jest tylko przy pobieraniu elementów macierzy:
>> B(3,1) ??? Index exceeds matrix dimensions.
Operator dwukropek, :, jest jednym z najbardziej użytecznych operatorów w MATLABie. Występuje w kilku różnych formach wyrażenie 1:10 produkuje wektor wierszowy o elementach od 1 do 10.
>> 1:10 ans = 1 2 3 4 5 6 7 8 9 10
Jeśli podamy inkrement to uzyskamy wektor o pożądanej różnicy między elementami np:
>> 10:-2.5:0 ans = 10.0000 7.5000 5.0000 2.5000 0Operator ten zastosowany w indeksie macierzy daje nam łatwy dostęp do jej fragmentów A(1:k,j) daje nam pierwszych k elementów j-tej kolumny macierzy A. Sam ":" oznacza wszystkie elementy danego wiersza lub kolumny np. sum(A(:,end)) oblicza sumę elementów ostatniej kolumny A
Do sklejania macierzy służy operator []. Np
B=ones(2,2); C=[B B+1; B+2 B+3]Możemy usuwać kolumny lub wiersze macierzy:
>> C=[1 2 3 4;5 6 7 8; 9 10 11 12; 13 14 15 16] C(2,:)=[]
patient.name = 'John Doe'; patient.billing = 127.00; patient.test = [79 75 73; 180 178 177.5; 220 210 205];Co zobaczymy jeśli teraz napiszemy w lini poleceń
patientAby dopisać kolejnego pacjenta napiszemy:
patient(2).name = 'Ann Lane'; patient(2).billing = 28.50; patient(2).test = [68 70 68; 118 118 119; 172 170 169];Jeśli teraz napiszemy
patientto nie zobaczymy wpisów w poszczególne pola ale rozmiary i nazwy pól Jeśli teraz dadamy
patient(3).name = 'Alan Johnson'to powstaną też pola
patient(3).billing patient(3).testwypełnione pustymi macierzami
Strukturę możemy zaalokować też przy użyciu funkcji:
str_array = struct('field1',val1,'field2',val2, ...)Poniżej mamy przykład inicjowania macierzy struktury na trzy sposoby:
Metoda | Składnia | Inicjalizacja | |
struct | weather(3) = struct('temp',72,'rainfall',0.0); | Powstaje macierz z trzema strukturami. Struktura weather(3) jest zainicjowana wartościami, które widać w wywołaniu. Struktury weather(1) i weather(2), są inicjalizowane pustymi macierzami . | |
struct with repmat | weather = repmat(struct('temp',72, 'rainfall',0.0),1,3); | Wszystkie struktury w macierzy weather są inickjalizowane tymi samymi wartościami. | |
struct with cell array syntax | weather = struct('temp',{68,80,72}, 'rainfall',{0.2,0.4,0.0}); | Struktury w macierzy weather są inicjalizowane wartościami wyspecyfikowanymi w macierzach komórek. . |
Większość poleceń Matlaba to funkcje, niektóre są wbudowane i działają bardzo szybko, ale znaczna część jest napisana w plikach tekstowych, które są interpretowane w czasie wykonywania (działają wolniej). Ma to jednak tą zaletę, że możemy do takiej funkcji zajrzeć i dużo się nauczyć, albo ją zmodyfikować! :-)
W matlabie można też tworzyć własne funkcje -- zbudowane z już istniejących. Plik zawierający funkcję musi nazywać się tak jak ta funkcja z roszerzeniem ".m" Pierwsza linia definiuje składnię wywołania funkcji np:
function [mean,stdev] = stat(x) %STAT Interesting statistics. n = length(x); mean = sum(x) / n; stdev = sqrt(sum((x - mean).^2)/n);Powyższy kod definiuje funkcję stat (powinna być zapisana w pliku stat.m). Funkcja ta przyjmuje jako argument wektor x i zwraca dwie wartości mean,stdev zmienne używane wewnątrz funkcji są lokalne tzn. nie są widoczne w workspace.
Przykład wywołania tej funkcji:
x=1:10; >> [m,s]=stat(x) m = 5.5000 s = 2.8723
W jednym pliku możemy mieć zdefiniowanych więcej funkcji, z tym, że są one widoczne tylko dla funkcji zawartych w tym samym pliku np. powyższą funkcję stat można zaimplementować tak:
function [mean,stdev] = stat(x) %STAT Interesting statistics. n = length(x); mean = avg(x,n); stdev = sqrt(sum((x-avg(x,n)).^2)/n); %------------------------- function mean = avg(x,n) %MEAN subfunction mean = sum(x)/n;
Powrót z funkcji następuje po osiągnięciu końca ciała funkcji. Wcześniejszy powrót warunkowy można uzyskać dzięki poleceniu return
%wytwarzamy wektor t o elementach od 1 do 1024 co 1 >> t=1:256; %rysujemy wektor t - domyślnie jest on łączony odcinkami prostej >> plot(t) % tu zobaczymy jakie mamy naprawdę elementy wektora >> plot(t,'g.') % dzielimy wszystkie elementy wektora przez 128 % (możemy sobie interpretować t jako czas 2s próbkowany co 1/128 sek). >> t=t/128; % robimy sinusa z okresem 1 (s) >> x=sin(2*pi*t); % rysujemy wektor x >> plot(x) % rysujemy wektor x względem wektora t >> plot(t,x) % rysujemy wektor x względem wektora % t linią ciągłą na niebiesko i na tym % tle rysujemy co piąty element x i t % czerwonymi kółkami >> plot(t,x,'b-',t(1:5:end),x(1:5:end),'ro')
y=sort(x2) plot(y)
x=randn(1000,1); y=x(find(x>2)); length(y) hist(x,20)
Instrukcje sterujące matlaba:
if I == J A(I,J) = 2; elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end
method = 'bilinear'; switch method case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') case 'nearest' disp('Method is nearest') otherwise disp('Unknown method.') end Method is linear
i=10 while i>1 i=i-1; disp(i) end
for k=1:10 disp(k*(1:10)) end