Docsity

MATLAB Functions: Definition, Syntax, Subfunctions, Anonymous Functions, Slides of Computer Programming

Partial preview of the text

Download MATLAB Functions: Definition, Syntax, Subfunctions, Anonymous Functions and more Slides Computer Programming in PDF only on Docsity!

Outline

Functions

M-files

Subfunctions

Anonymous functions

Examples

Factorial Function

Approximating Sine function

Sieve of Eratosthenes

Functions

Syntax

function [y1,..,yN] = func name(x1,..,xM) % Help text written here and it will be % shown until the first non−comment line

% Do stuff

end % optional

M-files

Function Files: define functions

function z = fname (x,y) % This file has to be named fname.m z = x + y; end

Script Files: collection of statements

% This file can have any valid filename a = input('Enter x: '); b = input('Enter y: '); c = fname(a,b); disp(c)

Variable Scope

Function Scope

function z = fname (x,y) % This file has to be named fname.m z = x + y; end

Global Scope

x = 5; disp(x); a = input('Enter x: '); b = input('Enter y: '); c = fname(a,b); disp(c); disp(x);

Anonymous Functions

not stored in a file

myfunc = @(x) (xˆ2); y = myfunc(3);

Approximating Sine Function

sin(x) = x −

x^3

x^5

x^7

∑^ ∞

n=

(−1)n^

x^2 n+

(2n + 1)!

What’s wrong with the code?

function s = approx sin (x, k) n = 0; s = 0; while n < (2k+1); s = s + (−1)ˆn + xˆn /factorial(n); n = n + 1; end

Primes Function

Question

What are all prime numbers ≤ N?

Using what we know

function p = primes1 (N) p = []; % creates an empty array for j = 1:N if isprime(j) % built−in isprime p = [p, j]; % expands the array end end end

A Better Primes Function

Add knowledge

All prime numbers, except 2, are odd numbers.

Updated code

function p = primes2 (N) if N>1, p = [2]; else p = []; end % check only odd numbers for j = 3:2:N if isprime(j) p = [p, j]; end end end

Why is it slow?

We check isprime for 3,5,7,9,11,13,15,..

Why do we check 9? 15? 21? 25? ..

Current Version

function p = primes2 (N) if N>1, p = [2]; else p = []; end % there are unnecessary checks for j = 3:2:N if isprime(j) p = [p, j]; end end end

Sieve of Eratosthenes

Prime Sieve

Idea: Eliminate the multiples of a number ahead of

time, so that we don’t need to check it.

Algorithm

% Create an array X of all 1's of length N % Set X(1) to 0 % Find position k of next 1 in the X array % If k is less than or equal to sqrt(N) % Set X(2k), X(3k), X(4*k) ... to zero % Go back to finding k % Else % Find the indices of all 1's in X array % These indices are prime numbers