230 likes | 411 Views
M-File, if and for. Arief Ramadhan. Create M-File. Select File -> New -> M-file from the MATLAB Desktop The Editor/Debugger will opens, if it is not already open, with an untitled file in the MATLAB current directory from which you can create an M-file. Functions.
E N D
M-File, if and for AriefRamadhan
Create M-File • Select File -> New -> M-file from the MATLAB Desktop • The Editor/Debugger will opens, if it is not already open, with an untitled file in the MATLAB current directory from which you can create an M-file.
Functions • Functions are M-files that can accept input arguments and return output arguments. • The name of the M-file and of the function should be the same. • Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.
The first line • The function definition line • The first line of a function M-file starts with the keyword function. • It gives the function name and order of arguments. input arguments • If no output argument is supplied, the result is stored in ans
The body • The rest of the file is the executable MATLAB code defining the function. • All variables introduced in the body of the function, are all local to the function; they are separate from any variables in the MATLAB workspace.
Example function mysquare(x) y = x*x; % this is comment % disp is used to show something disp (‘The result is:'); disp (y);
To save • File Save • File Save As • Where you assign a name to the file and save it. You do not need to type the .m extension because MATLAB automatically assigns the .m extension to the filename. • Please save in your own direcory
Running in Command Window • First, choose/browse your own directory in the Current Directory field
Running in Command Window (2) • Then, type your function name (mysquare) with the output/input arguments
Function with a return value • Using output argument • Example : function x=mytotal(a) % x is output argument x = a+5;
How to run • Using variable to save/hold the return value • Example
Function with multiple return value • Using multiple output argument • Separate by comma (,) • Using ‘[‘ and ‘]’ • Example : function [x,y]=mytotal2(a) x = a+5; y = a*5;
if • Conditionally execute statements if expression statements end • Example if x<2 z=7; end
For • Repeat statements a specific number of times • The columns of the expression are stored one at a time in the variable while the following statements, up to the end, are executed. • In practice, the expressionis almost always of the form scalar : scalar, • in which case its columns are simply scalars. • The scope of the for statement is always terminated with a matching end.
Example for i=1:10 disp(i); end
Exercise • Build a function/M-file to solve Ax2 + Bx + C