--- tags: Matlab Workshop --- # Lesson 4: Functions ## Functions **Functions** is a block of code which only runs when it is called. We can pass data (called arguments/parameters) into a function and the function can return some data as results. ![](https://i.imgur.com/UfuZt8F.png) In Matlab, we can construct a function using the ```function``` keyword. :::info Basic syntax of a **function** ```matlab function [out1, out2,... outN] = function_name(in1, in2, ...inN) equation expression end ``` ::: ## Example ```matlab function y = double_value(x) % The function "double_value" takes "x" as input, and output "y" y = 2 * x; end ``` When creating a user-defined function in MATLAB, **save the file in the current directory** or **add its directory to MATLAB's search path** so MATLAB can find and use the function. ```matlab >> double_value(3) % output: 6 ``` In MATLAB, **input parameters and output results** can be **any data type**, allowing functions to handle different types of data flexibly. ```matlab function out = flexibleFunction(input) if isnumeric(input) out = input + 10; % If input is numeric, add 10 elseif ischar(input) out = strcat("Hello, ", input); % If input is a string, concatenate elseif iscell(input) out = length(input); % If input is a cell array, return its length else out = "Unsupported type"; % Handle unsupported data types end end ``` ```matlab >> result1 = flexibleFunction(5) % Numeric input result1 = 15 >> result2 = flexibleFunction('John') % String input result2 = "Hello, John" >> result3 = flexibleFunction({1, 2, 3}) % Cell array input result3 = 3 ``` ## Basics of Function Declaration 1. **Functions with no inputs.** ```matlab function names = get_weekday_names() % or function names = get_weekday_names names = ["Monday", "Tuesday", "Wednesday", "Thurdays", "Friday", "Saturday", "Sunday"]; end ``` ```matlab >> names = get_weekday_names(); ``` 2. **Functions with no outputs.** ```matlab function print_info(name, age, gender) % or function [] = print_info(name, age, gender) fprintf("%s is a %d-year-old %s\n", name, age, gender); end ``` ```matlab >> print_info("Amy", 25, "girl"); % Amy is a 25-year-old girl >> print_info("Tom", 30); % Error: Not enough input arguments. ``` 3. **Multiple inputs and outputs.** We need to use square brackets for the multiple outputs. ```matlab function [out1, out2] = get_min_max(in) out1 = min(in); out2 = max(in); end ``` ```matlab >> arr = [-1, 12, 3, 0]; >> [a, b] = get_min_max(arr); >> disp(a); >> disp(b); ``` :::info ### Example From our previous exercises, we can write a function that checks the number of mismatches between two sequences. ```matlab function [mismatches] = checkNucleotideSequences(seq1, seq2) % This function compares two nucleotide sequences and counts mismatches. % Input: seq1, seq2 - two strings representing nucleotide sequences % Output: mismatches - number of mismatches % Initialize counter for mismatches mismatches = 0; % Ensure both sequences are the same length if length(seq1) ~= length(seq2) error('Sequences must be of equal length'); end % Loop through each nucleotide in the sequences for i = 1:length(seq1) if seq1(i) ~= seq2(i) mismatches = mismatches + 1; % Increment mismatches if nucleotides are different end end end ``` Run the function and see the results. ```matlab >> [mismatchCount] = checkNucleotideSequences('AGTCGA', 'AGTCCA') ``` ::: :::info ### Let's do an Exercise Write a function that creates a matrix with dimensions (length of seq1+1)×(length of seq2+1), initialized with zeros. Set the element at position (i+1,j+1) to 1 if the character at position i in seq1 matches the character at position j in seq2. **seq1**: AGTCGA **seq2**: AGTGCA ```matlab function % b = zeros(3, 7)  First create a zeros matrix % for loop Set the element at (i+1,j+1) to 1 if position i in seq 1 == position j in seq2 end ``` ::: :::spoiler ```matlab= function match_matrix = create_match_matrix(seq1, seq2) % Create a matrix with dimensions (length(seq1)+1) x (length(seq2)+1) % Each element starts as 0, and if seq1(i) == seq2(j), the element at % (i+1, j+1) is set to 1. % Get lengths of sequences len1 = length(seq1); len2 = length(seq2); % Initialize the matrix with zeros match_matrix = zeros(len1 + 1, len2 + 1); % Fill the matrix based on character matches for i = 1:len1 for j = 1:len2 if seq1(i) == seq2(j) match_matrix(i + 1, j + 1) = 1; % Match found, set to 1 end end end end ``` :::