Exercises

Please complete each exercise or answer the question before reviewing the posted solution comments.

Use the clear command before starting your work on a new problem to ensure that any existing variable name assignments don't interfere with your work on the new problem.

  1. Create a new m-file named BMI.m, write the code that translates this sequential algorithm to Matlab code, and save your file.

    1. Assign the weight (pounds) to a variable.
    2. Assign the height (feet) to a variable.
    3. Assign the remaining height (inches) to a variable.
    4. Convert weight from pounds to kilograms.
    5. Convert height from feet and inches to meters.
    6. Calculate the bmi according to the formula kg/m^2.
    7. Display the height, weight, and BMI.

    Here is one implementation that will work. There are others.

      % Get height and weight values from the user and calculate the BMI
      wt_lb = input('Enter your weight in pounds: ');
      ht_ft_in = input('Enter your height [ft in]: ');
      ht_ft = ht_ft_in(1);
      ht_in = ht_ft_in(2);
      ht_inches = ht_ft*12 + ht_in;
      wt_kg = wt_lb / 2.2;
      ht_m = ht_inches * 0.0254;
      bmi = wt_kg / ht_m^2 ;
      disp(['The Body Mass Index of a person who weighs ',num2str(wt_lb),' pounds and is ', ...
           num2str(ht_ft), ' ft ', num2str(ht_in), ' in is ', ...
            num2str(bmi)] );
      

    Reminder: Punctuation including blank spaces, periods, dashes, and many other non-letter characters in file names pose a problem for Matlab. Other than the underscore, don't use punctuation in M-file names, variable names, and function names.

    Notice how the individual values of the ht_ft_in matrix are accessed in later statements.

    Also, notice that each pseudo-code line in the algorithm is translated to one or more lines of code in the final program. There is rarely a one-to-one correspondance for this translation.

  2. Call the script you wrote above from the command window to calculate your BMI.

      >> BMI
      Enter your weight in pounds: 150
      Enter your height [ft in]: [5 11.5]
      The Body Mass Index of a person who weighs 150 pounds and is 5 ft 11.5 in is 20.6723
      >> 
      

    The bold-face type indicates what the user typed in the command window. The other text was output by the program based on the input received. Also, notice how the height was entered as one matrix with two values [ft in]. This technique allows multiple values to be saved in one variable name.