An example of function in Matlab | applied electronics engineering

An example of function in Matlab

By Applied Electronics - Wednesday, March 15, 2017 No Comments
Like other programming languages, Matlab also supports functions. Functions can make a program much easier to understand and debug especially if the program is complex and long. Learning how to write functions will be beneficial to you if you are using Matlab programming language for your work.

In user defined and inbuilt function in Matlab programming language tutorial we explained in details how functions are written in Matlab. In this tutorial we want to show simple and easy to remember function. For this we will write a function that calculates the resistors in series. When resistors are placed in series the resistance at the ends of the joined resistors is the total sum of the resistance.

The syntax of a function declaration in Matlab is as follows.

end

Now let's see how we can apply this to our problem. Let the name of the function be eq_series_resist and let the input argument be r. The output variable is say sres. Then we would write a matlab script for the function as follows,

function sres = eq_series_resist(r)
sres = sum(r)
end

The second line sres = sum(r) calculates the sum of the resistances.

An example of usages of this function and the output is as follows.

>> x = [10 20 15 16 5] ;
>> y = eq_series_resist(x);
>> y
66