
Advanced 2D Plotting Techniques in MATLAB Programming
Learn advanced programming techniques in MATLAB, focusing on 2D plots, strings, new data structures, logical operators, flow control, working with files, plot design, and more. Explore how to create various types of plots, customize their appearance with different markers and line styles, plot multiple curves on the same graph, add annotations, and handle legends and labels effectively. Enhance your MATLAB skills with practical examples and tips for better data visualization.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
MATLAB WORKSHOP Part 2: Advanced programming
Content Introduction to 2D plots Strings Printing New data structure: cell arrays New data structure: struct Logical operators and logical variables Flow control loops, conditional sentences and more Files opening and saving
2D plots Open a new window for plot This line of code will open a window with serial number 1 figure(1); 2D plot drawing plot(x1, y1, LineSpec1) where x1 is a vector containing the X-axis values, y1 is a vector containing Y-axis values and LineSpec1 contains a string that defines design of the plot: color, line style, etc. plot(x1, y1, :rs ) draws a dashed (:) red (r) line with square points (s) on the curve.
2D plots Design of the plots Symbol Marker type Symbol Marker type Symbol Marker type Symbol Marker type Upper triangle Circle Solid line Yellow ^ o - y v Downward triangle + Plus sign -- Dashed line m Magenta * Asterisk : Dotted line c Cyan > Right triangle . Point -. Dash-dotted r Red < Left triangle x Cross none No line g Green p Five-pointed star s Square b Blue h Six-pointed star d diamond w White none No markers k Black
2D plots Plot more than one curve One way: plot(x1,y1,LineSpec1, x2,y2,LineSpec2, x3,y3,LineSpec3) Second way: plot(x1,y1,LineSpec1) hold on; plot(x2,y2,LineSpec2) plot(x3,y3,LineSpec3) Example 1 0.8 theta= linspace(0,pi*5,100); phi= pi:pi/10:5.5*pi; plot(theta, sin(theta), 'r-o') hold on; plot(phi, cos(phi), 'k-o') 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 0 2 4 6 8 10 12 14 16 18
2D plots Additional design Caption for X-axis: Caption for Y-axis: Title of the plot: xlabel( angle [rad] ) ylabel( cosine ) title( trigonometric functions ) Legend: Value range for the axis: legend( sine , cosine ) xlim([2*pi, 4*pi]) Tip: you can write Greek letters with the help of \ : xlabel( \theta )
Strings Definition String is a type of variable containing a text between two quotes: str1= I am a good student ; Access to characters: str1(1) % I str1(8:end) % good student String concatenation str2= MATLAB ; str3=[str1, in , str2] % I am a good student in MATLAB
Useful functions for strings Function Actual command strcmp Comparison of 2 strings strcmpi Comparison lowercase versions of two strings strfind Finding of substring in string and returning the index of the first character of the substring strrep Replace substring with another substring num2str Number to string str2num String to number Examples str4= this is a string ; strcmp(str4, This is a string ) % 0 strcmpi(str4, This is a string ) % 1 strfind(str4, is ) % [3 6]
Printing Simple string printing x=3; % let s suppose x was received from an earlier calculation x_str= num2str(x); str_to_display= [ The result is: , x_str, meters ]; disp(str_to_display) % the result is: 3 meters
Printing Commands sprintf or fprintf to display variables in a particular format (both function are the same except fprintf can also send the output to the file) x=2/3; fprintf( The result is: %f , x) % The result is: 0.666667 fprintf( The result is: %0.3f , x) % The result is: 0.667 We use %f for decimal number and %d for integer (other options you can find in the doc for sprintf ) Example of printing more than 1 variable: x=3.69124; y=-1.82475; z=8.73269; fprintf( The coordinates are: [x,y,z] = [%0.2f , %0.2f , %0.2f] , x,y,z) % The coordinates are: [x,y,z] = [3.69 , -1.82 , 8.73]
Cells Cell array a data structure which contains variables of different types. Cells allow storing information in the most convenient way It is very useful for working with strings Definition 1 Creating and initializing a cell: cell1= cell(1,3) % empty cell array size 1X3 2 If we create cell with specific elements we use {} cell1= {'abc' , 1:5 , ones(3) }; Access to elements We usually use curly brackets {} cell1{2} % [1 2 3 4 5]
Cells Cell isolation can be done by standard brackets cell1(2) % 1X1 cell array containing the vector [1 2 3 4 5] Separating data from different cells: [var1, var2, var3]= cell1{:};
Useful functions Function Actual command cellfun Enables applying a function on each cell separately in a cell array num2cell Transforming a number/vector to a cell cell2mat Transforming a cell to a matrix (if possible) celldisp Displaying a cell array cellplot Illustrating a cell array
struc struct a data structure with configurable fields. The main function is to organize information Example struct1= struct( name , Yosi , age ,25, hobbies ,{ soccer , chess }) Or: struct1= struct; % initializing, optional struct1.name= Yosi ; struct1.age= 25; struct1.hobbies= { soccer , chess }; The various properties will be accessed by a point followed before the property name. Complex data structures can be made by combining matrices, cells and structs, etc. For example an array of structs struct2(1).name= Yosi ; struct2(2).name= Beni ;
Logical operations Logical operation returns 1 (true) or 0 (false) Logical operators operate on elements of vectors and matrices: Symbol Meaning Symbol Meaning NOT Not equal ~ ~= | OR == Equal & AND > Grater < Less c= 2<3; % 1 [6 7] ~= [6 6] % [0 1] (1>7) & (3==3) % 0
Flow control If the first expression is a logical true then the following commands are activated elseif can be applied as many times as it is needed at the end should be an else. if expression statements elseif expression statements else statements end
Flow control for loop: for index = values statements end values for indices can be vectors or strings of any type and dimensions. while loop: while expression statements end
Flow control switch case loop: (more effective alternative then if in some cases) switch variable_name case value_option1 statements otherwise is optional variable_name is a string or a scalar value_option is also string or a scalar case value_option2 statements . . . otherwise statements end
Flow control Try-catch loop: (optional catch) try MATLAB tries to execute statment1 and if it fails then execute statements 2 statements1 catch statements2 We use this option when we don t know if the commands will be able to run and we don t want MATLAB to stop an error. end
Flow control Useful commands inside the loop break stops the loop when reaching this command continue stops the current iteration of the loop and moves to the next iteration. return exits a function and returns the output error displays an error message in command window and stop running warning displays a warning message in the command window without stop running.
Working with files MATLAB saves and reads files in *.mat format Loading MATLAB files, which are in/not in the same folder: load filename % for files in MATLAB path load( c:\temp\filename.mat ) % for files not in path Saving: save filename var1 ... varN % for MATLAB path save( c:\temp\filename.mat , var1 ,..., varN ) As we don t specify the exact path, then MATLAB saves the file within the current path. You can read/write to other types of files with various commands: textread, csvread, xlsread, imread, audioread, xmlread.
Tips You can write one command on several lines by using ( ) disp( Unfortunately, no one can be told what the Matrix is. You have to see it for yourself ) Debugging Running the command once before getting started will cause MATLAB to stop at every line of code when encountering an error. dbstop if error You can also do this through the menu Once we are in debug mode, we gain access to the variables values at this stage of the run