MATLAB Cheat Sheet

MATLAB Cheat Sheet

MATLAB Cheat Sheet Useful Commands Vectors/Matrices Operations Vector Indexing a + b element-wise addition a - b element-wise subtraction a(1) the first element in vector clc clear command window a * b matrix multiplication a([1, 2, 5]) the first, second and fifth element in clear clear workspace a .* b element-wise multiplication vector clearx clear x from workspace a / b matrix division, mrdivide a(1:3) the first three elements of an vector close all close all figures a \ b mldivide a([1:3 5:6]) selected elements of a vector help function help for function a ./ b element-wise division a(end) the last element of the vector doc function documentation for function a ˆ b matrix power a(5:end) from the fifth to the last element in quit, exit terminates Matlab a .ˆ b vector edit Matlab element-wise power opens editor a.´ a(5:end-1) functionName transpose from the fifth to the penultimate ele- a´ format transpose + complex conjugate (Her- ment in vector sets command window output format a(1) = 10 short/long/compact mitian transpose) replace the first element in vector by [A B] concatenates 2 matrices horizontally 10 [A; B] concatenates 2 matrices vertically a([1 3 5]) = [2 replace elements in vector by values 2, cat(dim, A, B) concatenates 2 matrices 5 7] 5, and 7 length(A) size of longest dimension of A a([1 3 5]) = [] discard elements on position 1, 3, and Built in Functions/Constants size(A) size of A 5 ndims(A) number of dimensions of A numel(A) number of elements of A pi constant π tril(A) lower triangular part of matrix Matrix Indexing exp() exponential function triu(A) upper triangular part of matrix eps() floating point accuracy repmat(A, x, y) repeats copy of matrix A(1, 1) an element in the first row and first 1e6 1 × 106 reshape(A, x, y) changes dimensions of matrix column of matrix Inf infinity value squeeze(A) removes dimensions of size 1 A([1 5], 2:4) elements of matrix in the first and fifth NaN not-a-number value flip(A, dim) fliplr flips array (see also and rows and in columns two, three and 1i, 1j imaginary unit flipud ) four circshift(A, K, circularly shifts array A(n, :) the nth row in array dim) A(:, n) the nth column in array det(A) matrix determinant A(n, :) = [] discard nth row in array inv(A) Vectors/Matrices Creation matrix inversion A(:, n) = [] discard nth column in array roots(vec) polynomial roots A(1) the first element in array (linear index- round(A) round to nearest decimal integer (see ing) ceil floor fix x = [1 2 3] row vector 1 × 3 also , , and ) A(1:3) the first three elements of an array (lin- mod(A, n) x = [1; 2; 3] column vector 3 × 1 modulo operation ear indexing) rem(A, n) x = [1 2; 3 4] matrix 2 × 2 reminder after division a:b row vector [a; a + 1; : : : ; b] Logical Operators a:x:b row vector [a; a + x; : : : ; b] Logical Indexing linspace(a, b, n evenly spaced points between a and & logical AND n) b && short-circuit logical AND A(A == 3) extract elements equal to 3 logspace(a, b, n logarithmically spaced points be- | logical OR A(A > 5) extract elements greater than 5 n) tween 10a and 10b || short-circuit logical OR A(A > 5 & A < extract elements greater than 5 and at ones(n, m) matrix of values 1, [n × m] ~ not 30) the same time less than 30 zeros(n, m) matrix of values 0, [n × m] all function all eye(n) identity matrix, [n × n] any function any NaN(n, m) matrix of values NaN, [n × m] is* several function with logical output Inf(n, m) matrix of values true, [n × m] Debugging and Time Measurement true(n, m) matrix of logical ones, [n × m] Relation Operators false(n, m) matrix of logical zeros, [n × m] > greater then keyboard pauses execution rand(n, m) matrix of random uniformly dis- >= greater then or equal to dbcont resume execution (end debug mode) tributed values, [n × m] (see also < less then dbclear all removes all breakpoints randi and randn <= less then or equal to tic, toc start/stop time measurement diag() diagonal elements of matrix, vector -> == equal to profile profile code execution square matrix ~= not equal to on/off/clear/viewer Loops and Branching Basic Visualization writematrix(A, writes matrix to file (see also filename) readmatrix) if expression program branching using if-else figure opens empty figure imwrite(A, writes image to graphics file (see also ... axes creates Cartesian axes filename) imread) elseif plot(x, y) 2D line plot expression hold on/off retain current plot with new line fid = open file ... grid display/hide grid lines fopen(filename) else on/off/minor fclose(fid) close opened file ... title(txt) adds title to figure fgetl(fid) read line from file end xlabel(txt) adds x-axis label (same for y and z) fread(fid) read from binary file xlim([min, max]) sets limits of x-axis (same for y and z) fwrite(fid, A) write to binary file switch variable program branching using switch colormap view colormap case value1 stem(x, y) discrete stem plot Other Data Types ... pcolor(A) displays array data as colored cells A = cell(m, n) create cell array case {value2, surf(X, Y, Z) displays surface plot A = {x, y, z} create cell array value3} semilogx(X) semi-logarithmic plot (same for y) A(1, 1) smooth parentheses indexing, creates ... image(X) Show image from array subset cell array otherwise doc LineSpec plot parameters to customize curves A{1, 1} curly brackets indexing, access to data ... set(ref, Name, sets graphics object property in cell array end Value) B = create structure array get(ref, Name) query graphics object property value struct(field, for n = 1:10 for cycle ref.Name = Value dot notation, sets graphics object value) ... property B.field = value create structure array end Value = ref.Name dot notation, query graphics object double(A) converts array to double precision (see property value also single) while expression while cycle view(az, el) camera line of sight int8(A) converts array to 8-bit signed inte- ... ger (see also int16, int32, uint8, end Character arrays and Strings int18,...) datetime() array representing points in time (see break terminates execution of loop 'Hello world!' character vector is created using single also years, days, hours,...) continue pass control to next iteration quotation marks sparse(A) creates sparse matrix return return to invoking function A = char(B) convert another data type to character array Other useful functions Functions strfind(str, find string within other string find(X) find indices of nonzero elements fprintf(fileID, write data to text file function [out1, pattern) function definition format, A1) out2] = foo(in1, strcmp(str1, compare strings sprintf(format, format data into character vector in2) str2) strjoin(str, A1) @sin handle function definition join strings in array delimiter) eval(txt) executes Matlab expression in text @(x) xˆ2 + anonymous function definition feval(fun, x1) evaluate function sin(x) strtok(str, split string into parts delimiter) str2num(X) convert character array to numeric ar- nargin returns number of inputs regexp(str, reg) ray nargout returns number of outputs match regular expression str2double(X) convert characters to double precision varargin input variable allowing multiple inputs "Hello world!" numbers varargout output variable allowing multiple out- string is created using double quota- num2str(X) convert numeric array to character ar- puts tion marks A = string(B) convert another data type to string ray Set operations realmax largest positive floating-point num- File Handling ber (see also realmin, intmax, and intersect(A, B) set intersection of two arrays realmin) union(A, B) set union of two arrays dir folderName lists folder content interp1 1-D interpolation (see also interp2, setdiff(A, B) set difference of two arrays pwd identifies current folder interp3, and interpn) setxor(A, B) set exclusive or of two arrays exist name check existence of variable, function, fminbnd find minimum of single-variable func- unique(A) unique values in array folder, . tion sort(X) sort array elements cd(path) changes current folder fft Fast Fourier transform (see also fft2, sortrows(X) sorts rows of matrix mkdir(path, makes new folder fftn, ifft, fftshift,...) issorted(X) determines if the array is sorted folderName) timer creates object of timer to schedule exe- ismember(A, B) array elements that are members of set rmdir(path) remove folder cution of Matlab commands (see doc- array umentation) Shortcuts Command Window Shortcuts Matlab Editor Matlab File Suffix (not all) ENTER CTRL + line execution moves between tabs .m script/function/class ESC PG.UP/PG.DOWN delete whole line .mlx Matlab live script DEL CTRL + R delete one character (right to the cur- comment lines .p protected Matlab code CTRL + T sor) uncomment lines .mat binary data file BACKSPACE CTRL + D delete one character (left to the cursor) open highlighted m-file (func- .fig Matlab figure HOME moves cursor to the beginning of line tion/script) .mdl, .slx Simulink model END F5 moves cursor to the end of line execute current script/function .mdlp, .slxp Simulink protected model CTRL + " CTRL + S moves cursor to the beginning of next save current file (done automatically .mexa64, mex libraries F5 word after pressing .mexmaci64, CTRL + # CTRL + HOME moves cursor to the beginning of pre- jump to the beginning of file .mexw32, vious word CTRL + END jump to the end of file .mexw64 SHIFT + ENTER CTRL + !/ sends cursor to the next line (without jump word-by-word or expression-by- .mlappinstall APP file – installer execution) expression to the right/left .mlpkginstall support package – installer CTRL + K CTRL + W deletes all to the right of cursor close current file .mltbx toolbox file – installer CTRL + C CTRL + O forces interruption of Matlab activates open file dialog box .mn MuPAD notebook e.g.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    4 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us