Examples

  1. Translate this sequential algorithm to code and save it in a file named average3.m.

    1. Input the first value and save it as sum.
    2. Input the second value and save it as secondValue.
    3. Add the second value to the sum value.
    4. Input the third value.
    5. Add the third value to the sum value.
    6. Divide the sum by three and save the result as avg.
    7. Display the average to the user.

    Here's an example of code that translates the above algorithm. Note, there are multiple ways to correctly translate the algorithm.

      % Get values from the user and calculate average
      first = input('Enter the first value: ');
      sum = first;
      second = input('Enter the second value: ');
      sum = sum + second ;
      third = input('Enter the third value: ');
      sum = sum + third ;
      avg = sum / 3 ;
      disp(['The average of ',num2str(first),' and ',num2str(second), ' and ', ...
            num2str(third), ' is ', num2str(avg)] );
      

    To run your program script, press the run_button button.

    The use of several new built-in functions in Matlab are introduced here. They will be described more fully in the next two lesson topics. For now, here's a brief description of each new function used.

    The input() function is used to ask the user for input values. It accepts a string, called a prompt to display to the user so that they know what value to enter. Then it returns the value that the user entered so that the code can save it to a variable name.

    The disp() function is used to display output to the user. It accepts a single value or matrix of values to display. In the example above, the input to the disp() function is a matrix with eight string values.

    The num2str() function is used to convert a decimal value (a number) to a string of characters (digit characters).

    Be sure to try this program script and see how the input works from the user's point of view.