Matlab-Cheat-Sheet-for-Data-Science London Schoolof Economics PDF

Title Matlab-Cheat-Sheet-for-Data-Science London Schoolof Economics
Author Pori Niki
Course Nlp
Institution دانشگاه شهید بهشتی
Pages 10
File Size 508.7 KB
File Type PDF
Total Downloads 50
Total Views 125

Summary

Download Matlab-Cheat-Sheet-for-Data-Science London Schoolof Economics PDF


Description

Seediscussions,stats,andauthorprofilesforthispublicationat:https://www.researchgate.net/publication/317313022

MATLABCheatSheetforDataScience-LondonSchoolof Economics TechnicalReport·May2017 DOI:10.13140/RG.2.2.16859.77607

CITATIONS

READS

0

2,257

2authors: AliHabibnia

EghbalRahimikia

TheLondonSchoolofEconomicsandPoliticalScience

IranUniversityofScienceandTechnology

10PUBLICATIONS1CITATION

2PUBLICATIONS0CITATIONS

SEEPROFILE

Someoftheauthorsofthispublicationarealsoworkingontheserelatedprojects:

ForeignExchangeRateRiskMeasurementandManagemenViewproject

AllcontentfollowingthispagewasuploadedbyEghbalRahimikiaon02June2017. Theuserhasrequestedenhancementofthedownloadedfile.

SEEPROFILE

MATLAB Cheat Sheet for Data Science

map container

Map values to unique keys (dictionary).

Data import/export

Ali Habibnia

Eghbal Rahimikia

Last update: May, 2017 MATLAB r2017a

Preliminaries

xlsread/xlswrite load/save load/save -ascii dlmread/dlmwrite readtable/writetable fscanf/fprintf textscan fgetl fgets

fuc : This function or command requires a toolbox to execute.

Ways to get help doc doc command help help command lookfor (X) docsearch (X) demo which command

Display documentation. Display documentation for function. Display documentation in command window. Display help text in command window. Search all M-files for X. Search documentation for X. Access demonstration examples. Locate functions.

File extensions .m .mat .fig .p .mlx .mex .mlapp .mdl .slx .mdlp .slxp .mlappinstall .mltbx

A MATLAB script, function, or class. A MATLAB data, stores workspace. MATLAB figure or GUI template. MATLAB protected function file. MATLAB live script. MATLAB executable. MATLAB App Designer template. Simulink model. Simulink protected model. MATLAB app installer file. MATLAB toolbox file.

Common data types single double char string logical struct cell

Single precision numerical data (32 bits). Double precision numerical data (64 bits). Character array. String array. True (1) or false (0). Structure array. Cell array.

fread/fwrite fopen/fclose importdata readall imread/imwrite save filename save filename x,y load filename webread/webwrite (URL) websave (URL)

Read/write Excel spreadsheet. Load/save MATLAB variables. Load/save text files (.txt, .csv). Read/write ASCII-delimited file. Create/write table from file. Read/write data from/to text file. Read formatted data from text file. Read line from file, removing newline characters. Read line from file, keeping newline characters. Read/write from/to binary file. Open/close file. Load data from file. Read data from data-store. Read/write image file. Save all variables to .mat file. Save x,y variables to .mat file. Load all variables from .mat file. Read/write content from/to URL. Save data from URL to file.

Basic commands clc clear clear (X) close (X) close all ... clf whos (X) ver dir tic/toc beep ans pwd path pathtool mkdir cd what which lasterr lastwarn rehash home exit

MATLAB Cheat Sheet for Data Science - London School of Economics.

Clear command window. Clear workspace. Clear (X) from memory. Close figure (X). Close all figures. Continue entering statement. Clear current figure. Size, bytes, class, and attributes of (X). List MATLAB version and toolboxes. List current folder contents. Start/stop stopwatch timer. Produce system beep sound. Last answer. Current directory. View/change search directory. Open set path window. Make new directory. Change current directory. List of MATLAB files in folder. Find directory of functions. Last error message. Last warning message. Refresh caches. Send cursor home. Close MATLAB.

Create basic variables x=5 x=nan j:k j:i:k linspace(a,b,n) logspace(a,b,n) NaN(a,b) ones(a,b) zeros(a,b) eye(a) sparse(a,b) rand(a,b) randi(imax,a,b) randn(a,b) randperm(a) diag(x)

Define variable x to be 5. Define variable x to be Not-a-Number. Row vector from j to k (step size: 1). Row vector from j to k (step size: i). n numbers linearly spaced between a and b. n numbers logarithmically spaced between a and b. a × b matrix of NaN values. a × b matrix of 1 values. a × b matrix of 0 values. Identity matrix of size a. a × b sparse matrix. Uniform a × b random numbers in [0,1). Uniform a × b random integers in [1,imax]. Gaussian a × b random numbers. Integer random permutation in [1,a]. Square matrix (vector x: diagonal elements).

Basic math functions abs(x) sqrt(x) sign(x) round(x) ceil(x) fix(x) floor(x) complex(a,b) real(x) image(x) conj(x) log(x) log10(x) exp(x) rem(a,b) mod(a,b) lcm(a,b) gcd(a,b) nthroot(a,n)

Absolute value of x. Square root of x. Sign of x. Round of x. Round x toward positive infinity. Round x toward zero. Round x toward negative infinity. Complex array (z = a + bi). Real part of complex number. Imaginary part of complex number. Complex conjugate of x. Natural logarithm of x. Common logarithm of x. Exponential of x (ex ). Remainder after division of a by b. Remainder after division of a by b (modulo operation). Least common multiples of a and b. Greatest common multiples of a and b. Real n-th root of a.

Trigonometric functions #: sin, cos, tan, sec, or cot. #/#d(x) #h(x) a#/a#d(x) a#h(x) atan2/atan2d(x) hypot(x) deg2rad(x) rad2deg(x)

1 of 9

sine, cosine, tangent, secant, or cotangent. # of x in radians/degrees. Hyperbolic # of x. Inverse # of x in radians/degrees. Inverse hyperbolic # of x. Four-quadrant inverse tan of x in radians/degrees. Square root of sum of squares of x. Convert x from degrees to radians. Convert x from radians to degrees.

Linear algebra x=[1,2,3] x=[1;2;3] x=[1,2;3,4] x=[1,2;3,4;5,6] x={1,‘st’} sx.x1=[1,2,3] sx.x2={1,‘st’} x*y x+y x-y x.*y x./y A^n A.^n A’ inv(A) size(A) numel(A) min(A) cummin(A) max(A) cummax(A) sum(A) cumsum(A) mean(A) median(A) mode(A) prod(A) cumprod(A) diff(x,k) std(A) var(A) cov(A) corrcoef(A) eig(A) svd(A) norm(A) sort(A) sortrows(A) rank(A) chol(A) det(A) factor(A) perm(A)

1 × 3 vector (double array). 3 × 1 vector. 2 × 2 matrix (double array). 3 × 2 matrix. 1 × 2 cell array. 1 × 3 vector stored in sx structure array. 1 × 2 cell stored in sx structure array. Matrix multiplication. Element by element addition. Element by element subtraction. Element by element multiplication. Element by element division. Normal matrix power of A. Element-wise power of A. Transpose of A. Inverse. Size (rows and columns). Number of elements. Smallest elements. Cumulative minimum of array elements. Largest elements. Cumulative maximum of array elements. Sum of array elements. Cumulative sum of array elements. Average of elements. Median of elements. Mode of elements. Product of array elements. Cumulative product of array elements. Successive k-differences of x. Standard deviation. Variance. Covariance. Correlation coefficients (columns: random variables, rows: observations). Eigenvalues and eigenvectors. Singular values. Norms. Sorts vector from smallest to largest. Sorts rows of A in ascending order. Rank. Cholesky factorization of matrix. Determinant of square matrix. Prime factors. Permutations of the elements.

x([i,j]) If A is a matrix: A(i,j) A(i) A(i:j,l:m) A([a,b],[c,d]) A(:,i) A(:,[a,b]) A(i,:) A([i,j],:) A>i find(A>i) find(A==i) diag(A) tril(A) triu(A) A(i,j)=a A(:,i)=[a;b] A(i,:)=[] A([i,j],:)=[] A(A>m)=v A(A==m)=v arrayfun(func,A) bsxfun(func,A,B)

If A is a cell:

A{i,j} A(i,j)={a} A(:,i)={a;b} cellfun(func,A)

i-th and j-th elements.

* Element i,j of A (i, j, l, m ≥ 1). * Element i-th of A. * Elements in rows from i to j which are in columns from l to m. * a-th and b-th elements in rows and c-th and d-th elements in columns. * i-th column elements. a-th and b-th columns elements. * i-th row elements. * i-th and j-th rows elements. Logical array of elements higher than i. Indices of elements higher than i. Indices of elements equal to i. Elements in the principal diagonal of A. Lower triangular part of A. Upper triangular part of A. Replace element i,j of A with a. Replace i-th column of A with [a;b]. * Delete i-th row of A. * Delete i-th and j-th rows of A. Replace all elements over m with v. Replace all elements is equal to m with v. Apply a function to each element of A. Apply an element-wise binary operation specified by func to A and B.

char(x) strfind(x1,ptrn) strjoin(x) lower(x) upper(x) strcmp(x1,x2) strcmpi(x1,x2) split(x,dl) strsplit(x,dl) sprintf(‘fmt’,x1,x2) strvcat(x1,x2)

Regular expression regexp/regexpi(str,exp) regexprep(str,exp,rpc) regexptranslate(type,str)

Return true if: isvector(X) ismatrix(X) isstring(X) iscell(X) iscellstr(X) Define variable x to be ‘text’ (char). isstruct(X) istable(X) i-th part of char. islogical(X) i-th to j-th part of char. isscalar(X) Define variable x to be ‘text’ (str). isreal(X) Define more than one char. isrow(X) iscolumn(X) Define more than one str. isdiag(X) Element i,j of x (char). istril(X) Element i,j of x (str). istriu(X) i-th part of j-th char/str. isdir(X) i to m-th part of j-th char/str. Concatenate characters/strings.

Character and string

x=‘text’ x(i) x(i:j) x=string(‘text’) x={‘s1’,‘s2’} Accessing/assignment elements x=[string(‘st1’)... ,string(‘st2’)] If x is a vector: x{i,j} x(i) Element i-th of x (i, j ≥ 1). x(i,j) x(i:j) Elements from the i-th to the j-th of x. x{i}(j) x(i:end) Elements from the i-th to the last one of x. x{i:m}(j) x(:) All the elements of x. strcat(x1,x2)

MATLAB Cheat Sheet for Data Science - London School of Economics.

Search exp pattern in str char/ str (case sensitive/insensitive). Replace str which matches exp with the rpc. Translate str to regular expression by type as type of translation.

‘IS*’ functions

Return true where: isnan(X) isnumeric(X) Above matrix operations which are marked isinf(X) with asterisk(*). Output is cell array of isinteger(X) elements. isfloat(X) Element i,j of A (i, j, l, m ≥ 1). isbetween(X,a,b) Replace element i,j of A with cell {a}. Replace i-th column of A with cell {a;b}. ismember(X,B) Apply a function to each cell in A. ismissing(X,B)

st: string. char: character.

Create character from numeric array. Search x1 char/str for ptrn pattern. Construct char array using x char/str elements. Convert char/str to lowercase. Convert char/str to uppercase. Compare char/str of x1 and x2. Compare char/str of x1 and x2 (case insensitive). Split strings in string array (x) at dl delimiters. Split x char/str at dl delimiters. Format data based on fmt structure. Vertically concatenate x1 and x2 (ignore spaces).

2 of 9

Elements of X which Elements of X which Elements of X which Elements of X which Elements of X which Elements of X which (date and time). Elements of X which Elements of X which

are are are are are are

NaN. numeric. infinite. integer. floating-point. between a and b

are found in B. are missing.

X is a vector. X is a logical array. X is a string (char). X is a cell array. X is a cell array of strings. X is a structure. X is a table. X is a logical array. X is a scalar (size=[1,1]). There isn’t imaginary value in X. X is a row vector. X is a column vector. X is a lower diagonal matrix. X is a lower triangular matrix. X is a upper triangular matrix. X is directory (folder).

‘IS*’ functions... isequal(X,B) isequaln(X,B) issorted(X) isvarname(X)

X X X X

is equal to B. is equal to B (NaN values are equal). elements are in ascending order. is a valid MATLAB variable name.

Convert functions num2str(x) num2cell(x) num2int(x) num2hex(x) str2num(x) str2mat(x) str2double(x) str2func(x) cell2mat(x) cell2table(x) cell2struct(x) cellstr(x) mat2str(x) mat2cell(x) table2cell(x) table2array(x) table2struct(x) struct2cell(x) struct2table(x) int2str(x) datenum(x) datestr(x)

Convert numeric array (x) to char array. Convert numeric array (x) to cell array. Convert numeric array (x) to signed integer. Convert numeric array (x) to IEEE hexadecimal string. Convert char array (x) to numeric array. Convert char/str array (x) to matrix. Convert char/str array (x) to double precision. Convert char array (x) to function handle. Convert cell array (x) to matrix. Convert cell array (x) to table. Convert cell array (x) to structure array. Convert array x to cell array. Convert matrix (x) to char array. Convert matrix (x) to cell array. Convert table (x) to cell array. Convert table (x) to homogeneous array. Convert table (x) to structure array. Convert structure array (x) to cell array. Convert structure array (x) to table array. Convert integer (x) to char array. Convert date and time to a number. Convert date and time to string.

% This is a comment line. x=2; %This is a comment. y=3;

User-defined functions

function [out1,out2] = fun_name(in1,in2) ... end

Anonymous function structure: @ operator creates a function handle. f = @(x)(x.^2+exp(x)) % i.e. f(2) returns 11.3891.

for i = a:s:b MATLAB Commands end Break: break terminates the execution of for or while loop. Code lines after the break do not execute. In nested loops, break exits from the loop in which it mentions. Continue: continue passes control to the next iteration of for or while loop. In nested loops, continue passes the iteration in which it mentions.

Errors Common errors

Return: return forces MATLAB to return control to the invoking function before reaching to the end of that function.

Flow control If statement: An if statement can be followed by an (or more) optional elseif and an else statement, which is useful to test various condition. if (Condition_1) MATLAB Commands elseif (Condition_2) MATLAB Commands else MATLAB Commands end

Script vs. Function vs. Live script

Switch statement: Evaluate a statement and selection one of the cases based on this evaluation.

Function M-files: Can be executed by specifying some inputs and return some desired outputs.

switch (statement) case (value1) MATLAB Commands case (value2) MATLAB Commands end

Live scripts: Contain MATLAB codes, embedded outputs, formated texts, equations, and images together in a single environment. * Add comment: To put a comment within a line, type % followed by the comment in MATLAB command window, MATLAB script, or live script enviroment.

For loop statement: Loop from a to b in steps of s in the variable i.

Function structure: in1 and in2 are function inputs and out1 and out2 are function outputs.

Programming

Script M-files: Contain a list of commands that MATLAB simply executes in order. They are useful to batch simple sequences of commonly used commands together.

while (Condition) MATLAB Commands end

While loop statement: Repeat the commands while condition holds.

MATLAB Cheat Sheet for Data Science - London School of Economics.

Error using *: inner matrix dimensions must agree. The * operator performs matrix multiplication, where an NxM matrix is multiplied by an MxP matrix, resulting in an NxP matrix. Use .* instead of * to perform the element-wise multiplication. Index exceeds matrix dimensions. This error arises when you try to reference an element that doesn’t exist. Some useful functions to check sizes and number of elements are numel(), size(), and length(). The expression to the left of the equals sign is not a valid target for an assignment. This error message arises because of misuse of the = and == operators. The = operator does an assignment, and the == operator does a logical test for equality. Subscripted assignment dimension mismatch. This error message arises because of an attempt to assign a vector or matrix into a compartment that it does not fit in. Matrix dimensions must agree. This error message arises when you try to do operations on matrices with different dimensions. For example A+B when A is 2 × 2 and B is 2 × 3. Subscript indices must either be real positive integers or logicals. This error message arises because of indexing problem. For example A(1) is the first element in a matrix not A(0) (like other programming languages).

3 of 9

Handling errors Try, catch statement: try a statement, if it returns an error, catch it and do another statement.

‘distributed’: Partition listed functions out among the workers in a pool: zeros(5,5,‘distributed’), ones, false, true, NaN, inf, eye, rand, randi, and randn. ‘codistributed’: Access the arrays distributed among the workers in a pool: zeros(5,5,‘codistributed’), etc.

plot(x,y)

Plot y versus x (have same length).

try statements catch expression statements end

error(‘msg’) warning(‘msg’) assert(‘msg’) st=MException(ID... ,txt)

GPU: gpuDevice(idx) gpuArray(x) arrayfun(func,A) bsxfun(func,A,B)

Select GPU device specified by idx. Copy x array to GPU. Apply function to elements of A on GPU. Apply an element-wise binary operation specified by func to A and B on GPU. Transfer gpuArray to local workspace. Determine if x is stored in GPU.

Display message and abort function. Display warning message. Throw error if condition is false.

gather(A) existsOnGPU(x)

Capture information of a specific error and save it in the st object.

A basic calculation on GPU:

Input arguments: Line styles: Markers:

W=rand(5,‘single’); % Basic random numbers. GD=gpuArray(W); % Send W to GPU. GO=GD.*GD; % Execute multiplication on GPU.

Parallel computing (CPU & GPU) CPU:

plot(y) Plot y, with 1,2,3,... as the x axis. plot(x,f(x)) If f is a function, plot the points.

Colors:

Plotting & Figures

figure Create a new parallel pool (size is number of axis normal CPU workers). axis tight gcp Return the current parallel pool. axis equal ticBytes/... axis square tocBytes(gcp) Start/stop calculation of the bytes transferred axis fill to the workers. title(‘Title’) batch(‘scr’) Run a script or function on a worker. xlabel(‘lbl’) gather(A) Transfer distributed array to local workspace. ylabel(‘lbl’) zlabel(‘lbl’) legend(‘v’,‘w’) parfor: Replace for with parfor to execute code on CPU grid on/off workers or cores without any guaranteed order. box on/off datetick(‘x’,fm) parfor i = a:s:b xtickformat(fm) MATLAB Commands ytickformat(fm) end xlim([min,max]) ylim([min,max]) spmd: Execute code in parallel on workers of a pool. zlim([min,max]) hold on/off spmd text(x,y,text) statements spmd fn is a function: fplot(fn,rn) fmesh(fn,rn) parfeval: Directly execute a defined function on a specified fsurf(fn,rn) worker. fcontour(fn,rn) parpool(size)

p=gcp(); % Return current MATLAB pool. f=parfeval(p,@sum,4,3); % Parallel execution of 4+3.

MATLAB Cheat Sheet for Data Science - London School of Economics.

Open up a new figure window. Default axis limits and scaling behavior. Force axis to be equaled to data range. Force axis to be scaled equally. Axis lines with equal lengths. Lengths of each axis line fill the rectangle. Add a title at the top of the plot. Label the x axis as lbl. Label the y axis as lbl. Label the z axis as lbl. Add label to v and w curves. Include/Omit a grid in the plot. Display/hide the box outline around axes. Date formatted tick labels (fm is format). X-axis label format. Y-axis label format. X-axis limits from min to max. Y-axis limits from min to max. Z-axis limits from min to max. ...


Similar Free PDFs