Learning objectives
To familiarise yourself with Matlab syntax and some basic commands and to be able to do some basic operations on matrices. Please remember that Matlab has excellent documentation. Try typing ‘help ‘ to see if that will provide the answers you seek. Also, googling ‘matlab ‘ is helpful most of the times.
This part is intended for those you have some programming background, but have never used Matlab before. This article introduces basic concepts, and tries to give enough information to get the student ready for simple programming and solving home assignments.
Contents
- Short introduction to Matlab
- Printing information to Command Window
- Defining variables
- Accessing variable elements
- Putting different vectors/matrices together
- Vector and matrix operations
- Useful matrix/vectors functions
- Some keywords
- Saving/loading variables
- Deleting variables
- Enabling paths for functions
- Plotting, i.e. showing some numbers
- Cells and structures
- publish this manuscript
% Author : Santosh Tirunagari % Learning objectives: % - to familiarise yourself with Matlab syntax and some basic commands % - to be able to do some basic operations on matrices % % please remember that Matlab has excellent documentation. % Try typing 'help <function name>' to % see if that will provide the answers you seek. % Also, googling 'matlab <doing thing x>' is helpful most of the times. % This part is intended for those you have some programming background, but % have never used Matlab before. It introduced basic concepts, and tries to % give enough information to get the student ready for simple programming % and solving home assignments.
Short introduction to Matlab
% As you probably notices Matlab uses % for commenting % Double % in can be used to divide your code to cells. % Check that you have the cell mode enabled in the cell pulldown menu. % Now you can run the code cell-by-cell. Pressing ctrl-enter executes % the active cell. Note: cells in editor should not be confused with cell type, % introduced in part2 of this exercise.
Printing information to Command Window
Here are some commands for printing various info about state of your program. Strings are specified by using apostrophes. Formating of fprintf and sprintf is similar to C function fprintf.
fprintf('Hello World\n') disp('Another world'); fprintf('Variable %s equals %10.2f\n', 'bmw', rand);
Hello World Another world Variable bmw equals 0.81
Defining variables
Matlab is mostly aimed at computing (performing floating point operaations) and the default variable type is double, and its not necessary to define it beforehand. There are other numeric types but they are not needed for doing the home assignments. Matlab stores variables in so-called workspace, which can be accessed visually within Matlab environment. Statements in Matlab can be finished with semicolon ‘;’, but if semicolon is missing then Matlab prints the result of that statement to Command Window
singleval = 2; % create variable and assign it value 1 vector1 = [1 2 4 6]; % create array variable and assign values 1,2,4 and 6 to successive elements % arrays are 1xM matrices in Matlab, also called vectors vector2 = -1:10; % create vector with values from -1 to 10 matrix = [1 2; 0 1]; % create a matrix (notice semicolon ';') strval = 'str'; % create a string intvalue = int16(1); % create 16-bit integer variable with value 1 (typecasting) magicmat = magic(6) % define magic sqaure and print result to Command Window who % list all variables in current workspace whos % list all variables with details in current workspace
magicmat = 35 1 6 26 19 24 3 32 7 21 23 25 31 9 2 22 27 20 8 28 33 17 10 15 30 5 34 12 14 16 4 36 29 13 18 11 Your variables are: ans magicmat singleval vector1 intvalue matrix strval vector2 Name Size Bytes Class Attributes ans 1x30 60 char intvalue 1x1 2 int16 magicmat 6x6 288 double matrix 2x2 32 double singleval 1x1 8 double strval 1x3 6 char vector1 1x4 32 double vector2 1x12 96 double
Accessing variable elements
Sometimes we need to return specific elements of certain matrix or vector to be used in computations or just checking their values. This is accomplished by giving exact position within parentheses. Specifying all rows and columns is done with colon ‘:’, while multiple selection is done with another vector(s)
vector1(1,3) % return element at (row=1, column=3) vector1(3) % return element at position 3 (same as previous statement) % when a variable is a vector, it is enough to give single index magicmat(2,:) % return complete row=2 magicmat(:,1) % return whole column=1 magicmat([1 3],:) % return rows 1 and 3 and all columns strval(2) % second character of a string strval(2:3) % second and third character of a string
ans = 4 ans = 4 ans = 3 32 7 21 23 25 ans = 35 3 31 8 30 4 ans = 35 1 6 26 19 24 31 9 2 22 27 20 ans = 't' ans = 'tr'
Putting different vectors/matrices together
Adding and removing new rows/columns. When defining matrices, semicolon ‘;’ enters the new row. See also ‘help vertcat’, ‘help horzcat’ and ‘help cat’
matrix = [0 0; 1 0; 2 0]; % define 3x2 matrix nrow = [1 2]; % define 1x2 vector ncol = [1; 2; 3]; % define 3x1 vector mat2 = [matrix; nrow]; % add new row to create 4x2 matrix mat3 = [matrix, ncol]; % add new column to create 3x3 matrix mat3(:,2) = []; % remove second column mat2(1:2,:) = []; % remove first and second rows
Vector and matrix operations
Matlab is desinged for matrix operations and the syntax accommodates the goal by allowing variables to be matrices, and there is no need for loop statements to achieve the same goal.
mat1 = [1 0; 0 1]; mat2 = [-1 1; 1 2]; mat1 + mat2 % element-wise summation of matrices mat1 * mat2 % matrix multiplication mat1 .* mat2 % element-wise multiplication (notice the dot before star) mat1 / 2 % divide all elements of mat1 with 2 mat2^2 % matrix square mat2.^2 % element-wise square
ans = 0 1 1 3 ans = -1 1 1 2 ans = -1 0 0 2 ans = 0.5000 0 0 0.5000 ans = 2 1 1 5 ans = 1 1 1 4
Useful matrix/vectors functions
See help for length, size, numel, unique, ndims, isequal, ones, zeros, rand, magic, randn, logical
Some keywords
Looping is done with for or while statement. The example below sums over all elements of vector1. For defining your own functions see example_function.m
s = 0; for i = 1:length(vector1) % loop variable 'i' does not need to be defined before, but it will remain in workspace s = s + vector1(i); end s = 0; i = 1; while i <= length(vector1) % loop variable must be defined before while statement s = s + vector1(i); i = i + 1; end s = sum(vector1); % built-in function for summation % conditional statement 'if' must be enclosed with 'end' keyword a = 3; if a == 3 fprintf('%d\n', a); end if a == 1 fprintf('if(1)\n'); elseif a == 2 fprintf('if(2)\n'); else fprintf('else\n'); end
3 else
Saving/loading variables
See ‘help save’ and ‘help load’ for details
save myfile.mat singleval magicmat % save 2 variables in myfile.mat save('myfile.mat', 'singleval', 'magicmat', '-mat'); % same as above but in function form load myfile.mat magicmat % load 1 variables from myfile.mat load('myfile.mat', 'magicmat'); % same as above but in function form save('mytxt.txt', '-ascii', 'vector1'); % save in text format
Deleting variables
Removing unnecessary variable from memory is done with clear
clear singleval magicmat strval % remove specified variables clear
Enabling paths for functions
In order to get your function working which is located someplace else than the curretn path in Matlab, you must explicitly add it with addpath command, while rmpath removes the path. For example, if you are currently in c:\work (win) or /work (linux) folder, and your function ‘myfun.m’ is in subfolder codes (/work/codes/myfun.m) then you must add the path with ‘addpath codes’ to be able to call your myfun.m function. You can use relative path to your subfolder (absolute path also).
pwd % show the current working directory addpath(tempdir) % add temporary directory to Matlab path rmpath(tempdir) % remove temporary directory to Matlab path % addpath '/work/matlab/other/' % add some directory (absolute path)
Plotting, i.e. showing some numbers
Here are some examples how to show data graphically. For more possibilities and options, see plot, plot3, boxplot, scatter, mesh, surf, hist functions.
% Plotting a function in matlab is (usually) done numerically. That is, you % first create a grid of points on the x-axis and evaluate the function on % the points. The you draw a plot based on these function values. x = linspace(0,10); % linspace creates 100 equally spaced points between the given parameters plot(x,sin(x)); % create a new figure and plot results figure; % create a new figure plot(x, exp(x), 'rx') % plot with markers only hold on; % use this to include multiple graphs in the same figure plot(x, exp(x-1), 'k--') % plot with dashed line hold off % remove option to add more graphs to the current figure % gcf returns the handle of currently selected figure saveas(gcf, 'fig', 'fig'); % save figure with matlab extension saveas(gcf, 'fig', 'eps'); % save in eps format print(gcf, 'fig.png', '-r300', '-dpng'); % save in png format % creating many plots within the same figure figure; subplot(2,1,1); % create 'top' plot plot(x,sin(x)); subplot(2,1,2); % create 'bottom' plot plot(x,cos(x)); clf; % clear current figure plot(x, sin(x)); xlabel('ticks'); % add name for horizontal axis ylabel('sine'); % add name for vertical axis title('simple plot'); % add title for figure axis([-1 11 -2 2]); % modify the range of plot shg % show figure (if you are in command window)
Cells and structures
Organizing your variables into meaningful objects (another variables) can be done with cells and structures. For help see ‘help cell’ and ‘help struct’ Cells are collections of objects, where elements do not have to be of the same type. They are defined by using curly brackets, instead of parentheses.
cell1 = {'a', 1, [1 0; 1 1]}; cell1{1} % accessing elements similar to matrices but with curly brackets % return the contents of a cell cell1(1) % return a cell itself (not really important) cell2 = cell(3,2); % allocate memory for new cell cell{1,3} = ones(3,2); cell{2,1} = 'orange'; structure1.field1 = 2; % structures and fields structure1.field2 = 1:6; % fields can be of different type and size structure1.field3 = 'string'; structure2 = struct('field1', 1, 'field2', 'hello', 'field3', -5:5); structure2 = rmfield(structure2, 'field1') %to remove a field
ans = 'a' ans = 1×1 cell array {'a'} structure2 = struct with fields: field2: 'hello' field3: [-5 -4 -3 -2 -1 0 1 2 3 4 5]