Examples
Create a vector with the squares of the numbers 1 through 10.
1 2 4 9 16 25 36 49 64 81 100
for n = 1 : 10 squares(n) = n ^ 2 ; endThis works! Notice that we could, but we don't need to use the element-wise power operator since the value of
nis always a scalar.- Read height and weight data from a file named
player_data.txtand display the player number and BMI for each player in the data file. Use a for-loop to compute and display every player's information.For example, in a file named
team_bmi.m, enter this code:% Get the data from the file data = load('player_stats.txt'); % loads the player data in the variabledata[R C] = size(data); % Get the number of rows R and columns C % Do a little error checking to make sure that we have enough data to continue if C < 4 error('Not enough player data to continue. Each row needs: num ft in lbs'); end % Process each row in the data file for r = 1 : R num = data(r,1); % Get the player's number from the data matrix ht = data(r,2)*12 + data(r,3); % Get the player's height (in) wt = data(r,4); % Get the player's weight (lbs) bmi = BMI_standard(ht,wt); % Call the BMI_standard function to calculate % Create user-friendly output disp( [ 'Player #' num2str(num) ' has a BMI of ' num2str(bmi) ] ); endSome things to notice in our example code:
- The function
BMI_standardmust exist and be defined to calculate the BMI when the inputs are the height in inches and the weight in pounds. Reminder:
- Used the
sizefunction to find the number of rows and columns of the data matrix. Use these values to make sure that there is enough data to process. Display an error message and exit if there is not enough data. - Used the
dispcommand to display both text and numerical information. To produce that output, you need to use thenum2strfunction to change the numbers to strings so they will display properly. - Finished making the program user friendly, by using semicolons to hide all
of the intermediate answers that occur before and inside the
forloop where you output the BMIs.
Be sure to run and test the program on different data files to see if everything is working as you want it.
- The function