02.03.2016 Views

MATLAB by rudra pratap

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

100 Programming in <strong>MATLAB</strong>: Scripts and Functions<br />

A script file may contain any number of commands, including those that call<br />

built-in functions or functions written <strong>by</strong> you. Script files are useful when you have<br />

to repeat a set of commands several times. Here is an example.<br />

Example of a script file:<br />

of linear equations 1 :<br />

[ l 2r<br />

6<br />

r-1<br />

Let us write a script file to solve the following system<br />

T<br />

2r - 1<br />

3r<br />

(4. 1)<br />

or Ax = b. Clearly, A depends on the parameter r. We want to find the solution<br />

of the equation for various values of the parameter r. We also want to find, say, the<br />

determinant of matrix A in each case. Let us write a set of <strong>MATLAB</strong> commands<br />

that do the job and store these commands in a file called solvex.m. How you create<br />

this file, write the commands in it, and save the file depends on the computer you<br />

are using. In any case, you are creating a file called sol vex . m, which will be saved<br />

on some disk drive in some directory (or folder) .<br />

%----------- This is the script file ' solvex . m' -----------­<br />

% It solves equation (4.1) for x and also calculates det (A) .<br />

A [5 2*r r; 3 6 2*r-1; 2 r-1 3*r] ; % create matrix A<br />

b [2 ;3;5] ; % create vector b<br />

det_A = det (A)<br />

% find the determinant<br />

X = A\b<br />

% find x<br />

In this example, we have not put a semicolon at the end of the last two commands.<br />

Therefore, the results of these commands will be displayed on the screen<br />

when we execute the script file. The results will be stored in variables det_A and x,<br />

and these will be left in the workspace.<br />

Let us now execute the script in <strong>MATLAB</strong>.<br />

» clear all<br />

>> r = 1;<br />

>> solvex<br />

% clear the workspace<br />

% specify a value of r<br />

% execute the script file solvex .m<br />

det A<br />

64<br />

X<br />

-0. 0312<br />

0.2 344<br />

1.6875<br />

>> wh o<br />

This is the output. The values of the<br />

variables det_A and x appear on<br />

the screen because there is no semicolon<br />

at the end of the corresponding<br />

lines in the script file.<br />

Check the variables in the workspace.<br />

1 If you are not familiar with matrix equations, see Section 5.1.1 on page 135.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!