From 7bebfa3b9d946759d356c9b0c1c7be0e5aee552d Mon Sep 17 00:00:00 2001 From: Osvaldo Mendoza Date: Sun, 25 Aug 2013 01:32:33 -0400 Subject: Added MATLAB as a new language --- matlab.html.markdown | 260 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 matlab.html.markdown (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown new file mode 100644 index 00000000..507e9c85 --- /dev/null +++ b/matlab.html.markdown @@ -0,0 +1,260 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] +--- + +Matlab stands for Matrix Laboratory. It is a powerful numerical computing language commonly used in engineering and mathematics. + +If you have any feedback please feel free to reach me at +[@the_ozzinator](https://twitter.com/the_ozzinator), or +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```Matlab + + + +% Comments start with a percent sign. + +%{ Multi line comments look +something +like +this %} + +clear % Erases all your variables from memory +clc % Erases the writing on your Command Window +who % Displays all variables in memory +diary % History of session +ctrl-c % Abort current computation + +help command % Displays documentation for command in Command Window +lookfor command % Searches for a given command + + +% Output formatting +format short % 4 decimals in a floating number +format long % 15 decimals +fprintf + +% Variables & Expressions +myVariable = 4 % Notice Workspace pane shows newly created variable +myVariable = 4; % Semi colon suppresses output to the Command Window +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% Logicals +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % Not equal to -> ans = 1 +3 == 3 % equal to -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Strings +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Cells +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - returns a cell +char(a(1)) % ans = one - returns a string + + +% Vectors +x = [4 32 53 7 1] +x(2) % ans = 32, indices in Matlab start 1, not 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Column vector + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrices +A = [1 2 3; 4 5 6; 7 8 9] +% Rows are seperated with a semi colon, each element is seperated with space or comma +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(2,3) = 42 % Update row 2 col 3 with 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Creates a new matrix from the old one +%ans = + +% 5 42 +% 8 9 + +A(:,1) % All rows in column 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % All columns in row 1 +%ans = + +% 1 2 3 + +A(:, [3 1 2]) %Rearrange the columns of original matrix +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +A(1, :) =[] %Delete the first row of the matrix + +size(A) % ans = 3 3 + +A' % Transpose the matrix + +[A ; A] % Concatenation of matrices +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + + +%Element by Element Arithmetic VS Matrix Arithmetic +A * B % Matrix multiplication +A .* B % Multiple each element in A by its corresponding element in B + + +%Plotting +x = 0:.10:2*pi % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 +y = sin(x) +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 +plot(x,y1,’-’,x,y2,’--’,x,y3,’:’) % For multiple functions on one plot + + +% .mat files +% Save the variables in your Workspace + +%M-file Scripts +%A script file is an external file that contains a sequence of statements. +%Better than typing your code in the Command Window +%Have .m extensions + + +%M-file Functions +%Programs that accept inputs and return an output +%Have .m extensions +% double_input.m - naming your ,m file the same as you call it in the file is required +function output = double_input(x) + %double_input(x) returns twice the value of x + output = 2*x; +end +double_input(6) % ans = 12 + +%User input +a = input('Enter the value: ') + +%Reading in data +fopen(filename) + +%Output +disp(a) % Print out the value of variable a +disp('Hello World') % Print out a string +fprintf % More control display to Command Window + +%Conditional statements +if a > 15 + disp('Greater than 15') +elseif a == 23 + disp('a is 23') +else + disp('neither condition met') +end + +%Looping +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + + +%Connecting to a MySQL Database +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] %Example sql statement +a = fetch(conn, sql) %a will contain your data + + +% Common math functions +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand +randi + +% Common constants +pi +NaN +inf + +% Common matrix functions +zeros(m,n) % m x n matrix of 0's +ones(m,n) % m x n matrix of 1's +diag(A) % Extracts the diagonal elements of a matrix +eye(m,n) % Indentity matrix +inv(A) % Inverse of matrix A +det(A) % Determinant of A +eig(A) %Eigenvalues and eigenvectors of A +isempty(A) % Tests if array is empty +isequal(A, B) %Tests equality of two arrays +numel(A) %Number of elements in matrix + + + +``` + +## More on Matlab + +* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) -- cgit v1.2.3 From 9190044dee9fd71520fb67bc5fb3dd5a871ba3a8 Mon Sep 17 00:00:00 2001 From: Harshad Sabne Date: Fri, 6 Sep 2013 19:58:05 +0530 Subject: Update matlab.html.markdown Multiple function additions to "Common matrix functions" subsection. --- matlab.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 507e9c85..290e620c 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -250,7 +250,11 @@ eig(A) %Eigenvalues and eigenvectors of A isempty(A) % Tests if array is empty isequal(A, B) %Tests equality of two arrays numel(A) %Number of elements in matrix - +triu(x) % Returns the upper triangular part of x +tril(x) % Returns the lower triangular part of x +cross(A,B) % Returns the cross product of the vectors A and B +dot(A,B) % Returns the scalar product of the vectors A and B. A and B must be vectors of the same length. +transpose(A) % Returns the transpose of A ``` -- cgit v1.2.3 From 53e121b37df986f418168ec6a3b6287857d8464e Mon Sep 17 00:00:00 2001 From: Harshad Sabne Date: Fri, 6 Sep 2013 20:54:32 +0530 Subject: Update matlab.html.markdown Added subsection "Common vector functions" --- matlab.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 290e620c..3bcc4bbc 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -256,6 +256,17 @@ cross(A,B) % Returns the cross product of the vectors A and B dot(A,B) % Returns the scalar product of the vectors A and B. A and B must be vectors of the same length. transpose(A) % Returns the transpose of A +% Common vector functions +max %largest component +min %smallest component +length %length of a vector +sort %sort in ascending order +sum %sum of elements +prod %product of elements +median %median value +mean %mean value +std %standard deviation + ``` -- cgit v1.2.3 From b28900b889c27f8500a44d9f9bcad5244f1f79bd Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 8 Sep 2013 22:52:09 -0700 Subject: Fixed up so it builds --- matlab.html.markdown | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 3bcc4bbc..3c909153 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -10,10 +10,7 @@ If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). -```Matlab - - - +```matlab % Comments start with a percent sign. %{ Multi line comments look -- cgit v1.2.3 From f7ef4e6f8fde6ab60473f7ba8fd0f9d656cb87b3 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sat, 14 Sep 2013 22:17:41 +0100 Subject: Extend and improve MATLAB article --- matlab.html.markdown | 198 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 144 insertions(+), 54 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 3c909153..e72a95ea 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -2,9 +2,11 @@ language: Matlab contributors: - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + --- -Matlab stands for Matrix Laboratory. It is a powerful numerical computing language commonly used in engineering and mathematics. +MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or @@ -18,13 +20,23 @@ something like this %} +who % Displays all variables in memory +whos % Displays all variables in memory, with their types clear % Erases all your variables from memory +clear('A') % Erases a aprticualr variable +openvar('A') % Open variable in variable editor + clc % Erases the writing on your Command Window -who % Displays all variables in memory -diary % History of session +diary % Toggle writing Command Window text to file ctrl-c % Abort current computation +edit('myfunction.m') % Open function in editor +type('myfunction.m') % Print the source of function to Command Window + +profile viewer % Open profiler + help command % Displays documentation for command in Command Window +doc command % Displays documentation for command in Help Window lookfor command % Searches for a given command @@ -38,6 +50,7 @@ myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window 4 + 6 % ans = 10 8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 @@ -50,6 +63,12 @@ c = exp(a)*sin(pi/2) % c = 7.3891 3 > 1 || 4 > 1 % OR -> ans = 1 ~1 % NOT -> ans = 0 +% Logicals can be applied to matricies: +A > 5 +% for each element, if condition is true, that element is 1 in returned matrix +A[ A > 5 ] +% returns a vector containing the elements in A for which condition is true + % Strings a = 'MyString' length(a) % ans = 8 @@ -75,7 +94,7 @@ x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 % Matrices A = [1 2 3; 4 5 6; 7 8 9] -% Rows are seperated with a semi colon, each element is seperated with space or comma +% Rows are separated by a semicolon; elements are separated with space or comma % A = % 1 2 3 @@ -83,6 +102,10 @@ A = [1 2 3; 4 5 6; 7 8 9] % 7 8 9 A(2,3) % ans = 6, A(row, column) +A(6) % ans = 8 +% (implicitly concatenates columns into vector, then indexes into that) + + A(2,3) = 42 % Update row 2 col 3 with 42 % A = @@ -108,77 +131,125 @@ A(1,:) % All columns in row 1 % 1 2 3 -A(:, [3 1 2]) %Rearrange the columns of original matrix +[A ; A] % Concatenation of matrices (vertically) +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +[A , A] % Concatenation of matrices (horizontally) + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + + + +A(:, [3 1 2]) % Rearrange the columns of original matrix %ans = % 3 1 2 % 42 4 5 % 9 7 8 -A(1, :) =[] %Delete the first row of the matrix - size(A) % ans = 3 3 -A' % Transpose the matrix +A(1, :) =[] % Delete the first row of the matrix -[A ; A] % Concatenation of matrices -%ans = +A' % Hermitian transpose the matrix +% (the transpose, followed by taking complex conjugate of each element) +transpose(A) % Transpose the matrix, without taking complex conjugate -% 1 2 3 -% 4 5 42 -% 7 8 9 -% 1 2 3 -% 4 5 42 -% 7 8 9 -%Element by Element Arithmetic VS Matrix Arithmetic +% Element by Element Arithmetic vs. Matrix Arithmetic A * B % Matrix multiplication A .* B % Multiple each element in A by its corresponding element in B -%Plotting -x = 0:.10:2*pi % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 -y = sin(x) +% Plotting +x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 +y = sin(x); plot(x,y) xlabel('x axis') ylabel('y axis') title('Plot of y = sin(x)') axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 -plot(x,y1,’-’,x,y2,’--’,x,y3,’:’) % For multiple functions on one plot +plot(x,y1,'-',x,y2,'--',x,y3,':'') % For multiple functions on one plot +grid on % Show grid; turn off with 'grid off' + +axis square % Makes the current axes region square +axis equal % Set aspect ratio so data units are the same in every direction + +scatter(x, y); % Scatter-plot +hist(x); % Histogram +z = sin(x); +plot3(x,y,z); % 3D line plot -% .mat files -% Save the variables in your Workspace +pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value +contour(A) % Contour plot of matrix +mesh(A) % Plot as a mesh surface -%M-file Scripts -%A script file is an external file that contains a sequence of statements. -%Better than typing your code in the Command Window -%Have .m extensions +h = figure %C reate new figure object, with handle f +figure(h) %M akes the figure corresponding to handle h the current figure +% Properties can be set and changed through a figure handle +h = plot(x, y); +set(h, 'Color', 'r') +% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +set(h, 'LineStyle', '--') + % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line +get(h, 'LineStyle') -%M-file Functions -%Programs that accept inputs and return an output -%Have .m extensions -% double_input.m - naming your ,m file the same as you call it in the file is required + +% Variables can be saved to .mat files +save('myFileName.mat') % Save the variables in your Workspace +load('myFileName.mat') % Load saved variables into Workspace + + +% M-file Scripts +% A script file is an external file that contains a sequence of statements. +% They let you avoid repeatedly typing the same code in the Command Window +% Have .m extensions + + +% M-file Functions +% Like scripts, and have the same .m extension +% But can accept input arguments and return an output +% Also, they have their own workspace (ie. different variable scope) +% double_input.m - .m file name must be same as function name in file function output = double_input(x) %double_input(x) returns twice the value of x output = 2*x; end double_input(6) % ans = 12 -%User input + +% You can also have subfunctions and nested functions. +% Subfunctions are in the same file as the primary function, and can only be +% called from within that function. Nested functions are defined within another +% functions, and have access to both its workspace and their own workspace. + + +% User input a = input('Enter the value: ') -%Reading in data +% Reading in data fopen(filename) -%Output +% Output disp(a) % Print out the value of variable a disp('Hello World') % Print out a string -fprintf % More control display to Command Window +fprintf % Print to Command Window with more control -%Conditional statements +% Conditional statements if a > 15 disp('Greater than 15') elseif a == 23 @@ -187,7 +258,9 @@ else disp('neither condition met') end -%Looping +% Looping +% NB. looping over elements of a vector/matrix is slow! +% Where possible, use functions that act on whole vector/matrix at once for k = 1:5 disp(k) end @@ -197,8 +270,13 @@ while (k < 5) k = k + 1; end +% Timing code execution: 'toc' prints the time since 'tic' was called +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc -%Connecting to a MySQL Database +% Connecting to a MySQL Database dbname = 'database_name'; username = 'root'; password = 'root'; @@ -206,7 +284,7 @@ driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ conn = database(dbname, username, password, driver, dburl); -sql = ['SELECT * from table_name where id = 22'] %Example sql statement +sql = ['SELECT * from table_name where id = 22'] % Example sql statement a = fetch(conn, sql) %a will contain your data @@ -228,14 +306,19 @@ ceil(x) floor(x) round(x) rem(x) -rand -randi +rand % Uniformly distributed pseudorandom numbers +randi % Uniformly distributed pseudorandom integers +randn % Normally distributed pseudorandom numbers % Common constants pi NaN inf +% Solving matrix equations (if no solution, returns a least squares solution) +x=A\b % Solves Ax=b +x=B/a % Solves xa=B + % Common matrix functions zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's @@ -243,30 +326,37 @@ diag(A) % Extracts the diagonal elements of a matrix eye(m,n) % Indentity matrix inv(A) % Inverse of matrix A det(A) % Determinant of A -eig(A) %Eigenvalues and eigenvectors of A +eig(A) % Eigenvalues and eigenvectors of A +trace(A) % Trace of matrix - equivalent to sum(diag(A)) isempty(A) % Tests if array is empty +all(A) % Tests if all elements are nonzero or true +any(A) % Tests if any elements are nonzero or true isequal(A, B) %Tests equality of two arrays -numel(A) %Number of elements in matrix +numel(A) % Number of elements in matrix triu(x) % Returns the upper triangular part of x tril(x) % Returns the lower triangular part of x cross(A,B) % Returns the cross product of the vectors A and B -dot(A,B) % Returns the scalar product of the vectors A and B. A and B must be vectors of the same length. +dot(A,B) % Returns scalar product of two vectors (must have the same length) transpose(A) % Returns the transpose of A +flipl(A) % Flip matrix left to right % Common vector functions -max %largest component -min %smallest component -length %length of a vector -sort %sort in ascending order -sum %sum of elements -prod %product of elements -median %median value -mean %mean value -std %standard deviation - +max % largest component +min % smallest component +length % length of a vector +sort % sort in ascending order +sum % sum of elements +prod % product of elements +mode % modal value +median % median value +mean % mean value +std % standard deviation +perms(x) % list all permutations of elements of x ``` ## More on Matlab * The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* The official MATLAB Answers forum: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) + -- cgit v1.2.3 From 5bf3efe1652144648c4b8c0d3557180545d04cfa Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 01:41:27 +0100 Subject: Matlab: more plotting functions, anonymous functions, matrix factorisations, and other features. Fix some typos. --- matlab.html.markdown | 117 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 97 insertions(+), 20 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index e72a95ea..1e48618d 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -20,10 +20,17 @@ something like this %} +% commands can span multiple lines, using '...': + a = 1 + 2 + ... + + 4 + +% commands can be passed to the operating system +!ping google.com + who % Displays all variables in memory whos % Displays all variables in memory, with their types clear % Erases all your variables from memory -clear('A') % Erases a aprticualr variable +clear('A') % Erases a particular variable openvar('A') % Open variable in variable editor clc % Erases the writing on your Command Window @@ -43,6 +50,7 @@ lookfor command % Searches for a given command % Output formatting format short % 4 decimals in a floating number format long % 15 decimals +format bank % only two digits after decimal point - for financial calculations fprintf % Variables & Expressions @@ -63,7 +71,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891 3 > 1 || 4 > 1 % OR -> ans = 1 ~1 % NOT -> ans = 0 -% Logicals can be applied to matricies: +% Logicals can be applied to matrices: A > 5 % for each element, if condition is true, that element is 1 in returned matrix A[ A > 5 ] @@ -169,9 +177,18 @@ transpose(A) % Transpose the matrix, without taking complex conjugate % Element by Element Arithmetic vs. Matrix Arithmetic +% On their own, the arithmetic operators act on whole matrices. When preceded +% by a period, they act on each element instead. For example: A * B % Matrix multiplication A .* B % Multiple each element in A by its corresponding element in B +% There are several pairs of functions, where one acts on each element, and +% the other (whose name ends in m) acts on the whole matrix. +exp(A) % exponentiate each element +expm(A) % calculate the matrix exponential +sqrt(A) % take the square root of each element +sqrtm(A) % find the matrix whose square is A + % Plotting x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 @@ -181,9 +198,24 @@ xlabel('x axis') ylabel('y axis') title('Plot of y = sin(x)') axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 + plot(x,y1,'-',x,y2,'--',x,y3,':'') % For multiple functions on one plot -grid on % Show grid; turn off with 'grid off' +legend('Line 1 label', 'Line 2 label') % Label curves with a legend +% Alternative method to plot multiple functions in one plot. +% while 'hold' is on, commands add to existing graph rather than replacing it +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % A log-log plot +semilogx(x, y) % A plot with logarithmic x-axis +semilogy(x, y) % A plot with logarithmic y-axis + +fplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5 + +grid on % Show grid; turn off with 'grid off' axis square % Makes the current axes region square axis equal % Set aspect ratio so data units are the same in every direction @@ -197,11 +229,19 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure %C reate new figure object, with handle f -figure(h) %M akes the figure corresponding to handle h the current figure +h = figure % Create new figure object, with handle f +figure(h) % Makes the figure corresponding to handle h the current figure +close(h) % close figure with handle h +close all % close all open figure windows +close % close current figure window + +shg % bring an existing graphics window forward, or create new one if needed +clf clear % clear current figure window, and reset most figure properties -% Properties can be set and changed through a figure handle -h = plot(x, y); +% Properties can be set and changed through a figure handle. +% You can save a handle to a figure when you create it. +% The function gcf returns a handle to the current figure +h = plot(x, y); % you can save a handle to a figure when you create it set(h, 'Color', 'r') % 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black set(h, 'LineStyle', '--') @@ -209,22 +249,38 @@ set(h, 'LineStyle', '--') get(h, 'LineStyle') +% The function gcs returns a handle to the axes for the current figure +set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis + +% To creatw a figure that contains several axes in tiled positions, use subplot +subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots +plot(x1); title('First Plot') % plot something in this position +subplot(2,3,2); % select second position in the grid +plot(x2); title('Second Plot') % plot something there + + +% To use functions or scripts, they must be on your path or current directory +path % display current path +addpath /path/to/dir % add to path +rmpath /path/to/dir % remove from path +cd /path/to/move/into % change directory + + % Variables can be saved to .mat files save('myFileName.mat') % Save the variables in your Workspace load('myFileName.mat') % Load saved variables into Workspace - % M-file Scripts % A script file is an external file that contains a sequence of statements. % They let you avoid repeatedly typing the same code in the Command Window % Have .m extensions - % M-file Functions % Like scripts, and have the same .m extension % But can accept input arguments and return an output -% Also, they have their own workspace (ie. different variable scope) -% double_input.m - .m file name must be same as function name in file +% Also, they have their own workspace (ie. different variable scope). +% Function name should match file name (so save this example as double_input.m). +% 'help double_input.m' returns the comments under line beginning function function output = double_input(x) %double_input(x) returns twice the value of x output = 2*x; @@ -234,14 +290,26 @@ double_input(6) % ans = 12 % You can also have subfunctions and nested functions. % Subfunctions are in the same file as the primary function, and can only be -% called from within that function. Nested functions are defined within another +% called by functions in the file. Nested functions are defined within another % functions, and have access to both its workspace and their own workspace. +% If you want to create a function without creating a new file you can use an +% anonymous function. Useful when quickly defining a function to pass to +% another function (eg. plot with fplot, evaluate an indefinite integral +% with quad, find roots with fzero, or find minimum with fminsearch). +% Example that returns the square of it's input, assigned to to the handle sqr: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % find out more % User input a = input('Enter the value: ') -% Reading in data +% Stops execution of file and gives control to the keyboard: user can examine +% or change variables. Type 'return' to continue execution, or 'dbquit' to exit +keyboard + +% Reading in data (also xlsread/importdata/imread for excel/CSV/image files) fopen(filename) % Output @@ -249,10 +317,10 @@ disp(a) % Print out the value of variable a disp('Hello World') % Print out a string fprintf % Print to Command Window with more control -% Conditional statements -if a > 15 +% Conditional statements (the parentheses are optional, but good style) +if (a > 15) disp('Greater than 15') -elseif a == 23 +elseif (a == 23) disp('a is 23') else disp('neither condition met') @@ -316,14 +384,18 @@ NaN inf % Solving matrix equations (if no solution, returns a least squares solution) -x=A\b % Solves Ax=b -x=B/a % Solves xa=B +x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b. +x=b/A % Solves xA=b +inv(A) % calculate the inverse matrix +pinv(A) % calculate the pseudo-inverse % Common matrix functions zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's -diag(A) % Extracts the diagonal elements of a matrix +diag(A) % Extracts the diagonal elements of a matrix A +diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere eye(m,n) % Indentity matrix +linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 inv(A) % Inverse of matrix A det(A) % Determinant of A eig(A) % Eigenvalues and eigenvectors of A @@ -340,13 +412,18 @@ dot(A,B) % Returns scalar product of two vectors (must have the same length) transpose(A) % Returns the transpose of A flipl(A) % Flip matrix left to right +% Alternative forms for matrices +[L, U, P] = lu(A) % LU decomposition: PA = LU +[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues +[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order + % Common vector functions max % largest component min % smallest component length % length of a vector sort % sort in ascending order sum % sum of elements -prod % product of elements +prod % product of elements mode % modal value median % median value mean % mean value -- cgit v1.2.3 From 372e79a3fb3c6db8d350defae65d30f0a7f48663 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 01:42:13 +0100 Subject: Relabel a section to 'Matrix Factorisations --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 1e48618d..eaf50e8e 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -412,7 +412,7 @@ dot(A,B) % Returns scalar product of two vectors (must have the same length) transpose(A) % Returns the transpose of A flipl(A) % Flip matrix left to right -% Alternative forms for matrices +% Matrix Factorisations [L, U, P] = lu(A) % LU decomposition: PA = LU [P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues [U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order -- cgit v1.2.3 From e0f9a4dab392c13df8c909eb4a58a81950c30e1a Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 01:48:02 +0100 Subject: Comment explaining LU decomposition --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index eaf50e8e..98d085da 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -413,7 +413,7 @@ transpose(A) % Returns the transpose of A flipl(A) % Flip matrix left to right % Matrix Factorisations -[L, U, P] = lu(A) % LU decomposition: PA = LU +[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix [P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues [U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order -- cgit v1.2.3 From 28f0e163e2d4d5d8e55f484fef93190dda4e7593 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 02:53:32 +0100 Subject: Typos --- matlab.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 98d085da..e9874f21 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -249,10 +249,10 @@ set(h, 'LineStyle', '--') get(h, 'LineStyle') -% The function gcs returns a handle to the axes for the current figure +% The function gca returns a handle to the axes for the current figure set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis -% To creatw a figure that contains several axes in tiled positions, use subplot +% To create a figure that contains several axes in tiled positions, use subplot subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots plot(x1); title('First Plot') % plot something in this position subplot(2,3,2); % select second position in the grid @@ -394,7 +394,7 @@ zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's diag(A) % Extracts the diagonal elements of a matrix A diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere -eye(m,n) % Indentity matrix +eye(m,n) % Identity matrix linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 inv(A) % Inverse of matrix A det(A) % Determinant of A -- cgit v1.2.3 From 3eb4dbab9a4a6d9082f424289f982e8489138033 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Sun, 15 Sep 2013 16:06:26 +0100 Subject: Typos --- matlab.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index e9874f21..27b00eba 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -199,7 +199,7 @@ ylabel('y axis') title('Plot of y = sin(x)') axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 -plot(x,y1,'-',x,y2,'--',x,y3,':'') % For multiple functions on one plot +plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot legend('Line 1 label', 'Line 2 label') % Label curves with a legend % Alternative method to plot multiple functions in one plot. @@ -403,7 +403,7 @@ trace(A) % Trace of matrix - equivalent to sum(diag(A)) isempty(A) % Tests if array is empty all(A) % Tests if all elements are nonzero or true any(A) % Tests if any elements are nonzero or true -isequal(A, B) %Tests equality of two arrays +isequal(A, B) % Tests equality of two arrays numel(A) % Number of elements in matrix triu(x) % Returns the upper triangular part of x tril(x) % Returns the lower triangular part of x -- cgit v1.2.3 From 4ddcd660f8d08196c8628156d3e1bc0f1c785d97 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Wed, 18 Sep 2013 18:05:29 +0100 Subject: Explain difference between command and function syntax --- matlab.html.markdown | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 27b00eba..b8e552e2 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -37,8 +37,8 @@ clc % Erases the writing on your Command Window diary % Toggle writing Command Window text to file ctrl-c % Abort current computation -edit('myfunction.m') % Open function in editor -type('myfunction.m') % Print the source of function to Command Window +edit('myfunction.m') % Open function/script in editor +type('myfunction.m') % Print the source of function/script to Command Window profile viewer % Open profiler @@ -62,6 +62,17 @@ myVariable = 4; % Semi colon suppresses output to the Command Window a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 +% Calling functions can be done in either of two ways: +% Standard function syntax: +load('myFile.mat', 'y') +% Command syntax: +load myFile.mat y % no parentheses, and spaces instead of commas +% Note the lack of quote marks in command form: inputs are always passed as +% literal text - cannot pass variable values. Also, can't reveive output: +[V,D] = eig(A) % this has no equivalent in command form + + + % Logicals 1 > 5 % ans = 0 10 >= 10 % ans = 1 @@ -384,8 +395,10 @@ NaN inf % Solving matrix equations (if no solution, returns a least squares solution) +% The \ and / operators are equivalent to the functions mldivide and mrdivide x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b. x=b/A % Solves xA=b + inv(A) % calculate the inverse matrix pinv(A) % calculate the pseudo-inverse -- cgit v1.2.3 From c3fcedf70f1b607166be3e8ba64d0da25ccfddb0 Mon Sep 17 00:00:00 2001 From: James Scott-Brown Date: Wed, 18 Sep 2013 18:08:31 +0100 Subject: Fix typo - misspelt 'receive' --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index b8e552e2..15ff2303 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -68,7 +68,7 @@ load('myFile.mat', 'y') % Command syntax: load myFile.mat y % no parentheses, and spaces instead of commas % Note the lack of quote marks in command form: inputs are always passed as -% literal text - cannot pass variable values. Also, can't reveive output: +% literal text - cannot pass variable values. Also, can't receive output: [V,D] = eig(A) % this has no equivalent in command form -- cgit v1.2.3 From 77f28824af30ae86c89a4785439c65bd5a623a8a Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 6 Apr 2014 19:46:58 -0700 Subject: Fix syntax highlight. Fixes #587 (Instead of using #588) --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 15ff2303..9baefe68 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -181,7 +181,7 @@ size(A) % ans = 3 3 A(1, :) =[] % Delete the first row of the matrix -A' % Hermitian transpose the matrix +ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) transpose(A) % Transpose the matrix, without taking complex conjugate -- cgit v1.2.3 From 4fb3361655e59e9314d1a4f48fe76def08bc07fe Mon Sep 17 00:00:00 2001 From: masdeseiscaracteres Date: Thu, 17 Jul 2014 15:45:53 +0200 Subject: Small correction: "flipl" should be "fliplr" Added "flipud" also --- matlab.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 9baefe68..d9a82890 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -423,7 +423,8 @@ tril(x) % Returns the lower triangular part of x cross(A,B) % Returns the cross product of the vectors A and B dot(A,B) % Returns scalar product of two vectors (must have the same length) transpose(A) % Returns the transpose of A -flipl(A) % Flip matrix left to right +fliplr(A) % Flip matrix left to right +flipud(A) % Flip matrix up to down % Matrix Factorisations [L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix -- cgit v1.2.3 From 7d52148acf1ca5228e7882769345bc4da36c787f Mon Sep 17 00:00:00 2001 From: Ben Eysenbach Date: Wed, 3 Sep 2014 20:33:55 -0400 Subject: Matlab syntax error --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index d9a82890..9dae8ef2 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -85,7 +85,7 @@ load myFile.mat y % no parentheses, and spaces instead of commas % Logicals can be applied to matrices: A > 5 % for each element, if condition is true, that element is 1 in returned matrix -A[ A > 5 ] +A( A > 5 ) % returns a vector containing the elements in A for which condition is true % Strings -- cgit v1.2.3 From 759f7349d2ff36ee7d9b28c20d9ce690de413683 Mon Sep 17 00:00:00 2001 From: Srinivas Gorur-Shandilya Date: Mon, 27 Oct 2014 16:52:14 -0400 Subject: cleaned up code, added struct docs cleaned up code, added struct docs --- matlab.html.markdown | 49 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 9dae8ef2..42db6ad7 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -40,36 +40,40 @@ ctrl-c % Abort current computation edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window -profile viewer % Open profiler +profile on % turns on the code profiler +profile of % turns off the code profiler +profile viewer % Open profiler -help command % Displays documentation for command in Command Window -doc command % Displays documentation for command in Help Window -lookfor command % Searches for a given command +help command % Displays documentation for command in Command Window +doc command % Displays documentation for command in Help Window +lookfor command % Searches for a command in all other commands % Output formatting -format short % 4 decimals in a floating number -format long % 15 decimals -format bank % only two digits after decimal point - for financial calculations -fprintf +format short % 4 decimals in a floating number +format long % 15 decimals +format bank % only two digits after decimal point - for financial calculations +fprintf('text') % print "text" to the screen +disp('text') % print "text" to the screen % Variables & Expressions -myVariable = 4 % Notice Workspace pane shows newly created variable +myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 % Calling functions can be done in either of two ways: % Standard function syntax: -load('myFile.mat', 'y') +load('myFile.mat', 'y') % arguments within parantheses, spererated by commas % Command syntax: -load myFile.mat y % no parentheses, and spaces instead of commas +load myFile.mat y % no parentheses, and spaces instead of commas % Note the lack of quote marks in command form: inputs are always passed as % literal text - cannot pass variable values. Also, can't receive output: -[V,D] = eig(A) % this has no equivalent in command form +[V,D] = eig(A); % this has no equivalent in command form +[~,D] = eig(A); % if you only want D and not V @@ -100,6 +104,10 @@ a = {'one', 'two', 'three'} a(1) % ans = 'one' - returns a cell char(a(1)) % ans = one - returns a string +% Structures +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; % Vectors x = [4 32 53 7 1] @@ -160,6 +168,10 @@ A(1,:) % All columns in row 1 % 4 5 42 % 7 8 9 +% this is the same as +vertcat(A,A); + + [A , A] % Concatenation of matrices (horizontally) %ans = @@ -168,6 +180,8 @@ A(1,:) % All columns in row 1 % 4 5 42 4 5 42 % 7 8 9 7 8 9 +% this is the same as +horzcat(A,A); A(:, [3 1 2]) % Rearrange the columns of original matrix @@ -180,10 +194,13 @@ A(:, [3 1 2]) % Rearrange the columns of original matrix size(A) % ans = 3 3 A(1, :) =[] % Delete the first row of the matrix +A(:, 1) =[] % Delete the first column of the matrix +transpose(A) % Transpose the matrix, which is the same as: +A' ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) -transpose(A) % Transpose the matrix, without taking complex conjugate + -- cgit v1.2.3 From e1bdeff354c2535515ea31e733a5f078a2f469eb Mon Sep 17 00:00:00 2001 From: Srinivas Gorur-Shandilya Date: Tue, 28 Oct 2014 09:56:18 -0400 Subject: clarified lookfor --- matlab.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 42db6ad7..121f16de 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -46,7 +46,8 @@ profile viewer % Open profiler help command % Displays documentation for command in Command Window doc command % Displays documentation for command in Help Window -lookfor command % Searches for a command in all other commands +lookfor command % Searches for command in the first commented line of all functions +lookfor command -all % searches for command in all functions % Output formatting -- cgit v1.2.3 From 3f69c38ba3594eb93d86d1f4b2456241ffe9b14a Mon Sep 17 00:00:00 2001 From: xk liu Date: Thu, 30 Oct 2014 11:07:40 +0800 Subject: [matlab/en] Fix block comment syntax. The %{ and %} operators must appear alone on the lines that immediately precede and follow the block of help text. Do not include any other text on these lines. Reference: http://www.mathworks.com/help/matlab/matlab_prog/comments.html --- matlab.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 121f16de..2b9077d5 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -15,10 +15,12 @@ If you have any feedback please feel free to reach me at ```matlab % Comments start with a percent sign. -%{ Multi line comments look +%{ +Multi line comments look something like -this %} +this +%} % commands can span multiple lines, using '...': a = 1 + 2 + ... -- cgit v1.2.3 From 1992190cd010c21115c00c84ae168d0c004023e2 Mon Sep 17 00:00:00 2001 From: Harry Mumford-Turner Date: Tue, 18 Nov 2014 10:19:11 +0000 Subject: Temp fix for Matlab syntax highlighting The single quote messed up the rest of the file. --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 2b9077d5..9de41275 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -200,7 +200,7 @@ A(1, :) =[] % Delete the first row of the matrix A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: -A' +A one ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) -- cgit v1.2.3 From 90c27c72cfbd1fc2fa4b5700a5e08efc6c3ed874 Mon Sep 17 00:00:00 2001 From: Kado Date: Thu, 16 Jul 2015 18:43:13 +0300 Subject: Update matlab.html.markdown --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 9de41275..00f4c53a 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -43,7 +43,7 @@ edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window profile on % turns on the code profiler -profile of % turns off the code profiler +profile off % turns off the code profiler profile viewer % Open profiler help command % Displays documentation for command in Command Window -- cgit v1.2.3 From 960ee4a1856db8eadb96277bb2422edfa8f2a81c Mon Sep 17 00:00:00 2001 From: Gabriel Halley Date: Wed, 7 Oct 2015 23:11:24 -0400 Subject: removing whitespace all over --- matlab.html.markdown | 78 ++++++++++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 39 deletions(-) (limited to 'matlab.html.markdown') diff --git a/matlab.html.markdown b/matlab.html.markdown index 00f4c53a..02fe5962 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -6,7 +6,7 @@ contributors: --- -MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. +MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or @@ -16,7 +16,7 @@ If you have any feedback please feel free to reach me at % Comments start with a percent sign. %{ -Multi line comments look +Multi line comments look something like this @@ -62,10 +62,10 @@ disp('text') % print "text" to the screen % Variables & Expressions myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 -a = 2; b = 3; +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 % Calling functions can be done in either of two ways: @@ -73,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891 load('myFile.mat', 'y') % arguments within parantheses, spererated by commas % Command syntax: load myFile.mat y % no parentheses, and spaces instead of commas -% Note the lack of quote marks in command form: inputs are always passed as +% Note the lack of quote marks in command form: inputs are always passed as % literal text - cannot pass variable values. Also, can't receive output: [V,D] = eig(A); % this has no equivalent in command form [~,D] = eig(A); % if you only want D and not V @@ -103,7 +103,7 @@ a(2) % ans = y % Cells -a = {'one', 'two', 'three'} +a = {'one', 'two', 'three'} a(1) % ans = 'one' - returns a cell char(a(1)) % ans = one - returns a string @@ -113,7 +113,7 @@ A.c = [1 2]; A.d.e = false; % Vectors -x = [4 32 53 7 1] +x = [4 32 53 7 1] x(2) % ans = 32, indices in Matlab start 1, not 0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -123,7 +123,7 @@ x = [4; 32; 53; 7; 1] % Column vector x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 % Matrices -A = [1 2 3; 4 5 6; 7 8 9] +A = [1 2 3; 4 5 6; 7 8 9] % Rows are separated by a semicolon; elements are separated with space or comma % A = @@ -132,7 +132,7 @@ A = [1 2 3; 4 5 6; 7 8 9] % 7 8 9 A(2,3) % ans = 6, A(row, column) -A(6) % ans = 8 +A(6) % ans = 8 % (implicitly concatenates columns into vector, then indexes into that) @@ -171,7 +171,7 @@ A(1,:) % All columns in row 1 % 4 5 42 % 7 8 9 -% this is the same as +% this is the same as vertcat(A,A); @@ -183,7 +183,7 @@ vertcat(A,A); % 4 5 42 4 5 42 % 7 8 9 7 8 9 -% this is the same as +% this is the same as horzcat(A,A); @@ -201,21 +201,21 @@ A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: A one -ctranspose(A) % Hermitian transpose the matrix +ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) -% Element by Element Arithmetic vs. Matrix Arithmetic +% Element by Element Arithmetic vs. Matrix Arithmetic % On their own, the arithmetic operators act on whole matrices. When preceded % by a period, they act on each element instead. For example: A * B % Matrix multiplication A .* B % Multiple each element in A by its corresponding element in B -% There are several pairs of functions, where one acts on each element, and +% There are several pairs of functions, where one acts on each element, and % the other (whose name ends in m) acts on the whole matrix. -exp(A) % exponentiate each element +exp(A) % exponentiate each element expm(A) % calculate the matrix exponential sqrt(A) % take the square root of each element sqrtm(A) % find the matrix whose square is A @@ -233,7 +233,7 @@ axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot legend('Line 1 label', 'Line 2 label') % Label curves with a legend -% Alternative method to plot multiple functions in one plot. +% Alternative method to plot multiple functions in one plot. % while 'hold' is on, commands add to existing graph rather than replacing it plot(x, y) hold on @@ -271,9 +271,9 @@ clf clear % clear current figure window, and reset most figure properties % Properties can be set and changed through a figure handle. % You can save a handle to a figure when you create it. -% The function gcf returns a handle to the current figure +% The function gcf returns a handle to the current figure h = plot(x, y); % you can save a handle to a figure when you create it -set(h, 'Color', 'r') +set(h, 'Color', 'r') % 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black set(h, 'LineStyle', '--') % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line @@ -298,8 +298,8 @@ cd /path/to/move/into % change directory % Variables can be saved to .mat files -save('myFileName.mat') % Save the variables in your Workspace -load('myFileName.mat') % Load saved variables into Workspace +save('myFileName.mat') % Save the variables in your Workspace +load('myFileName.mat') % Load saved variables into Workspace % M-file Scripts % A script file is an external file that contains a sequence of statements. @@ -312,11 +312,11 @@ load('myFileName.mat') % Load saved variables into Workspace % Also, they have their own workspace (ie. different variable scope). % Function name should match file name (so save this example as double_input.m). % 'help double_input.m' returns the comments under line beginning function -function output = double_input(x) +function output = double_input(x) %double_input(x) returns twice the value of x output = 2*x; end -double_input(6) % ans = 12 +double_input(6) % ans = 12 % You can also have subfunctions and nested functions. @@ -325,8 +325,8 @@ double_input(6) % ans = 12 % functions, and have access to both its workspace and their own workspace. % If you want to create a function without creating a new file you can use an -% anonymous function. Useful when quickly defining a function to pass to -% another function (eg. plot with fplot, evaluate an indefinite integral +% anonymous function. Useful when quickly defining a function to pass to +% another function (eg. plot with fplot, evaluate an indefinite integral % with quad, find roots with fzero, or find minimum with fminsearch). % Example that returns the square of it's input, assigned to to the handle sqr: sqr = @(x) x.^2; @@ -336,12 +336,12 @@ doc function_handle % find out more % User input a = input('Enter the value: ') -% Stops execution of file and gives control to the keyboard: user can examine +% Stops execution of file and gives control to the keyboard: user can examine % or change variables. Type 'return' to continue execution, or 'dbquit' to exit keyboard % Reading in data (also xlsread/importdata/imread for excel/CSV/image files) -fopen(filename) +fopen(filename) % Output disp(a) % Print out the value of variable a @@ -363,8 +363,8 @@ end for k = 1:5 disp(k) end - -k = 0; + +k = 0; while (k < 5) k = k + 1; end @@ -382,7 +382,7 @@ password = 'root'; driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ -conn = database(dbname, username, password, driver, dburl); +conn = database(dbname, username, password, driver, dburl); sql = ['SELECT * from table_name where id = 22'] % Example sql statement a = fetch(conn, sql) %a will contain your data @@ -394,7 +394,7 @@ tan(x) asin(x) acos(x) atan(x) -exp(x) +exp(x) sqrt(x) log(x) log10(x) @@ -426,7 +426,7 @@ pinv(A) % calculate the pseudo-inverse zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's diag(A) % Extracts the diagonal elements of a matrix A -diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere +diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere eye(m,n) % Identity matrix linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 inv(A) % Inverse of matrix A @@ -452,15 +452,15 @@ flipud(A) % Flip matrix up to down [U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order % Common vector functions -max % largest component -min % smallest component +max % largest component +min % smallest component length % length of a vector -sort % sort in ascending order -sum % sum of elements +sort % sort in ascending order +sum % sum of elements prod % product of elements mode % modal value -median % median value -mean % mean value +median % median value +mean % mean value std % standard deviation perms(x) % list all permutations of elements of x -- cgit v1.2.3