Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

MATLAB Cheat Sheet, Lecture notes of Matlab skills

MATLAB Cheat Sheet. Useful Commands clc clear command window ... terminates Matlab edit. functionName opens Matlab editor format short/long/compact.

Typology: Lecture notes

2021/2022

Uploaded on 08/05/2022

dirk88
dirk88 🇧🇪

4.5

(206)

3.2K documents

Partial preview of the text

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



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved