mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-24 18:11:38 +00:00
Merge pull request #347 from jamesscottbrown/master
[matlab/en] Extend MATLAB article
This commit is contained in:
commit
ffc6d5aa60
@ -20,18 +20,25 @@ something
|
|||||||
like
|
like
|
||||||
this %}
|
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
|
who % Displays all variables in memory
|
||||||
whos % Displays all variables in memory, with their types
|
whos % Displays all variables in memory, with their types
|
||||||
clear % Erases all your variables from memory
|
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
|
openvar('A') % Open variable in variable editor
|
||||||
|
|
||||||
clc % Erases the writing on your Command Window
|
clc % Erases the writing on your Command Window
|
||||||
diary % Toggle writing Command Window text to file
|
diary % Toggle writing Command Window text to file
|
||||||
ctrl-c % Abort current computation
|
ctrl-c % Abort current computation
|
||||||
|
|
||||||
edit('myfunction.m') % Open function in editor
|
edit('myfunction.m') % Open function/script in editor
|
||||||
type('myfunction.m') % Print the source of function to Command Window
|
type('myfunction.m') % Print the source of function/script to Command Window
|
||||||
|
|
||||||
profile viewer % Open profiler
|
profile viewer % Open profiler
|
||||||
|
|
||||||
@ -43,6 +50,7 @@ lookfor command % Searches for a given command
|
|||||||
% Output formatting
|
% Output formatting
|
||||||
format short % 4 decimals in a floating number
|
format short % 4 decimals in a floating number
|
||||||
format long % 15 decimals
|
format long % 15 decimals
|
||||||
|
format bank % only two digits after decimal point - for financial calculations
|
||||||
fprintf
|
fprintf
|
||||||
|
|
||||||
% Variables & Expressions
|
% Variables & Expressions
|
||||||
@ -54,6 +62,17 @@ myVariable = 4; % Semi colon suppresses output to the Command Window
|
|||||||
a = 2; b = 3;
|
a = 2; b = 3;
|
||||||
c = exp(a)*sin(pi/2) % c = 7.3891
|
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 receive output:
|
||||||
|
[V,D] = eig(A) % this has no equivalent in command form
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
% Logicals
|
% Logicals
|
||||||
1 > 5 % ans = 0
|
1 > 5 % ans = 0
|
||||||
10 >= 10 % ans = 1
|
10 >= 10 % ans = 1
|
||||||
@ -63,7 +82,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
|
|||||||
3 > 1 || 4 > 1 % OR -> ans = 1
|
3 > 1 || 4 > 1 % OR -> ans = 1
|
||||||
~1 % NOT -> ans = 0
|
~1 % NOT -> ans = 0
|
||||||
|
|
||||||
% Logicals can be applied to matricies:
|
% Logicals can be applied to matrices:
|
||||||
A > 5
|
A > 5
|
||||||
% for each element, if condition is true, that element is 1 in returned matrix
|
% for each element, if condition is true, that element is 1 in returned matrix
|
||||||
A[ A > 5 ]
|
A[ A > 5 ]
|
||||||
@ -169,9 +188,18 @@ transpose(A) % Transpose the matrix, without taking complex conjugate
|
|||||||
|
|
||||||
|
|
||||||
% 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 % Matrix multiplication
|
||||||
A .* B % Multiple each element in A by its corresponding element in B
|
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
|
% Plotting
|
||||||
x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1
|
x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1
|
||||||
@ -181,9 +209,24 @@ xlabel('x axis')
|
|||||||
ylabel('y axis')
|
ylabel('y axis')
|
||||||
title('Plot of y = sin(x)')
|
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
|
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'
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
% 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 square % Makes the current axes region square
|
||||||
axis equal % Set aspect ratio so data units are the same in every direction
|
axis equal % Set aspect ratio so data units are the same in every direction
|
||||||
|
|
||||||
@ -199,9 +242,17 @@ mesh(A) % Plot as a mesh surface
|
|||||||
|
|
||||||
h = figure % Create new figure object, with handle f
|
h = figure % Create new figure object, with handle f
|
||||||
figure(h) % Makes the figure corresponding to handle h the current figure
|
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
|
||||||
|
|
||||||
% Properties can be set and changed through a figure handle
|
shg % bring an existing graphics window forward, or create new one if needed
|
||||||
h = plot(x, y);
|
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
|
||||||
|
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
|
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
|
||||||
set(h, 'LineStyle', '--')
|
set(h, 'LineStyle', '--')
|
||||||
@ -209,22 +260,38 @@ set(h, 'LineStyle', '--')
|
|||||||
get(h, 'LineStyle')
|
get(h, 'LineStyle')
|
||||||
|
|
||||||
|
|
||||||
|
% 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 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
|
||||||
|
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
|
% Variables can be saved to .mat files
|
||||||
save('myFileName.mat') % Save the variables in your Workspace
|
save('myFileName.mat') % Save the variables in your Workspace
|
||||||
load('myFileName.mat') % Load saved variables into Workspace
|
load('myFileName.mat') % Load saved variables into Workspace
|
||||||
|
|
||||||
|
|
||||||
% M-file Scripts
|
% M-file Scripts
|
||||||
% A script file is an external file that contains a sequence of statements.
|
% 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
|
% They let you avoid repeatedly typing the same code in the Command Window
|
||||||
% Have .m extensions
|
% Have .m extensions
|
||||||
|
|
||||||
|
|
||||||
% M-file Functions
|
% M-file Functions
|
||||||
% Like scripts, and have the same .m extension
|
% Like scripts, and have the same .m extension
|
||||||
% But can accept input arguments and return an output
|
% But can accept input arguments and return an output
|
||||||
% Also, they have their own workspace (ie. different variable scope)
|
% 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 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
|
%double_input(x) returns twice the value of x
|
||||||
output = 2*x;
|
output = 2*x;
|
||||||
@ -234,14 +301,26 @@ double_input(6) % ans = 12
|
|||||||
|
|
||||||
% You can also have subfunctions and nested functions.
|
% You can also have subfunctions and nested functions.
|
||||||
% Subfunctions are in the same file as the primary function, and can only be
|
% 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.
|
% 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
|
% User input
|
||||||
a = input('Enter the value: ')
|
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)
|
fopen(filename)
|
||||||
|
|
||||||
% Output
|
% Output
|
||||||
@ -249,10 +328,10 @@ disp(a) % Print out the value of variable a
|
|||||||
disp('Hello World') % Print out a string
|
disp('Hello World') % Print out a string
|
||||||
fprintf % Print to Command Window with more control
|
fprintf % Print to Command Window with more control
|
||||||
|
|
||||||
% Conditional statements
|
% Conditional statements (the parentheses are optional, but good style)
|
||||||
if a > 15
|
if (a > 15)
|
||||||
disp('Greater than 15')
|
disp('Greater than 15')
|
||||||
elseif a == 23
|
elseif (a == 23)
|
||||||
disp('a is 23')
|
disp('a is 23')
|
||||||
else
|
else
|
||||||
disp('neither condition met')
|
disp('neither condition met')
|
||||||
@ -316,14 +395,20 @@ NaN
|
|||||||
inf
|
inf
|
||||||
|
|
||||||
% Solving matrix equations (if no solution, returns a least squares solution)
|
% Solving matrix equations (if no solution, returns a least squares solution)
|
||||||
x=A\b % Solves Ax=b
|
% The \ and / operators are equivalent to the functions mldivide and mrdivide
|
||||||
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
|
% Common matrix functions
|
||||||
zeros(m,n) % m x n matrix of 0's
|
zeros(m,n) % m x n matrix of 0's
|
||||||
ones(m,n) % m x n matrix of 1'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
|
||||||
eye(m,n) % Indentity matrix
|
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
|
inv(A) % Inverse of matrix A
|
||||||
det(A) % Determinant of A
|
det(A) % Determinant of A
|
||||||
eig(A) % Eigenvalues and eigenvectors of A
|
eig(A) % Eigenvalues and eigenvectors of A
|
||||||
@ -340,6 +425,11 @@ dot(A,B) % Returns scalar product of two vectors (must have the same length)
|
|||||||
transpose(A) % Returns the transpose of A
|
transpose(A) % Returns the transpose of A
|
||||||
flipl(A) % Flip matrix left to right
|
flipl(A) % Flip matrix left to right
|
||||||
|
|
||||||
|
% Matrix Factorisations
|
||||||
|
[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
|
||||||
|
|
||||||
% Common vector functions
|
% Common vector functions
|
||||||
max % largest component
|
max % largest component
|
||||||
min % smallest component
|
min % smallest component
|
||||||
|
Loading…
Reference in New Issue
Block a user