# Introductory Programming

## Introductory Programming with MATLAB


       
  


MATLAB provides scripting and automation tools that can simplify repetitive computational tasks. For example, a series of commands executed in a MATLAB session to solve a problem can be saved in a script file called an m-file. An m-file can be executed from the command line by typing the name of the file or by pressing the run button in the built-in text editor tool bar.    
  

### Script Files

A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m. By typing the filename at the command prompt, we can run the script and obtain results in the command window. 

A sample m-file named ThermalConductivity.m is displayed in Text Editor below. Note the triangle (in green) run button in the tool bar, pressing this button executes the script in the command window. 

Now let us see how an m-file is created and executed.

### The input Function

Notice that the script we have created above is not interactive and computes the total volume only for the variables defined in the m-file. To make this script interactive we will make some changes to the existing AcetyleneBottle.m by adding input function and save it as AcetyleneBottleInteractive.m.  

The syntax for input is as follows:

### The disp Function

As you might have noticed, the output of our script is not displayed in a well-formatted fashion. Using disp, we can control how text or arrays are displayed in the command window. For example, to display a text string on the screen, type in disp('Hello world!'). This command will return our friendly greeting as follows: Hello world!

disp(variable) can be used to display only the value of a variable. To demonstrate this, issue the following command in the command window: 
We have created a row vector with 5 elements. The following is displayed in the command window:
Now if we type in disp(b) and press enter, the variable name will not be displayed but its value will be printed on the screen: 
The following example demonstrates the usage of disp function. 

### The num2str Function

The num2str function allows us to convert a number to a text string. Basic syntax is str = num2str(A) where variable A is converted to a text and stored in str. Let's see how it works in AcetyleneBottleInteractiveDisp.m. Remember to save the file with a different name before editing it, for example, AcetyleneBottleInteractiveDisp1.m.


### The fopen and fclose Functions

The first command is used to open or create a file. The basic syntax for fopen is as follows: 
For example, fo = fopen('output.txt', 'w'); opens or creates a new file named output.txt and sets the permission for writing. If the file already exists, it discards the existing contents.
fclose command is used to close a file. For example, if we type in fclose(fo);, we close the file that was created above.

### The fprintf Function 

fprintf function writes formatted data to the computer monitor or a file. This command can be used to save the results of a calculation to a file. To do this, first we create or open an output file with fopen, second we issue the fprintf command and then we close the output file with fclose.     

The simplified syntax for fprintf is as follows: 
Upon running the file, the output.txt file will display the following:

### Loops

In programming, a loop executes a set of code a specified number of times or until a condition is met. 


### For Loop

This loop iterates an index variable from an initial value using a specified increment to a final value and runs a set of code. The for loop syntax is the following:

    for loop_index=vector_statement
      code
      ...
      code
    end


### While Loop

Like the for loop, a while loop executes blocks of code over and over again however it runs as long as the test condition remains true. The syntax of a while loop is

    while test_condition
     code
     ...
     code
    end 


### The diary Function

Instead of writing a script from scratch, we sometimes solve problems in the Command Window as if we are using a scientific calculator. The steps we perform in this fashion can be used to create an m-file. For example, the diary function allows us to record a MATLAB session in a file and retrieve it for review. Reviewing the file and by copying relevant parts of it and pasting them in to an m-file, a script can be written easily. 

Typing diary at the MATLAB prompt toggles the diary mode on and off. As soon as the diary mode is turned on, a file called diary is created in the current directory. If you like to save that file with a specific name, say for example problem16, type 


>> diary problem16.txt.
 
A file named problem16.txt will be created. The following is the content of a diary file called problem16.txt. Notice that in that session, the user is executing the four files we created earlier. The user's keyboard input and the resulting display output is recorded in the file. The session is ended by typing diary which is printed in the last line. This might be useful to create a record of your work to hand in with a lab or to create the beginnings of an m-file.

### Style Guidelines

Try to apply the following guidelines when writing your scripts:

1. Share your code or programs with others, consider adopting one of  Creative Commons or  GNU General Public License schemes
2. Include your name and contact info in the opening lines
3. Use comments liberally
4. Group your code and use proper indentation
5. Use white space liberally
6. Use descriptive names for your variables
7. Use descriptive names for your m-files

### Summary of Key Points

1. A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m.
2. Functions such as input, disp and num2str can be used to make scripts interactive,
3. fopen, fprintf and fclose functions are used to create output files,
4. A for loop is used to repeat a specific block of code a definite number of times.
5. A while loop is used to repeat a specific block of code an indefinite number of times, until a condition is met.
6. The diary function is useful to record a MATLAB command window session from which an m-file can be easily created,
7. Various style guidelines covered here help improve our code.