Trouble With Table And Graph (Real World Application of Loops and Branches)

4 views (last 30 days)
Frank Maley
Frank Maley on 4 Nov 2019
Commented: Steven Lord on 7 Nov 2019
I have to use MATLAB to write a code, employing at least one loop to determine the actual difference in salary between men and women, the Earnings Ratio, and Pay Gap each year between 2018 and 2028. The output should be a neatly formatted table in the command window with the heading shown below. Also using the fprintf function display in the command window the total difference in pay between a man and a woman over the 20 year period. I tried to create a table but it says my rows aren't even. I may have messed up above that. This is what I have right now.
M_vec= zeros(1,20);
W_vec= zeros(1,20);
ER_vec= zeros(1,20);
PG_vec= zeros(1,20);
format bank
for final = a
M_vec(final)= M;
W_vec(final)= W;
AverageMensSalary = M_vec(final);
AverageWomensSalary = W_vec(final);
DifferenceinAnnualSalary= M_vec(final)-W_vec(final);
EarningsRatio= ER_vec(final);
PayGap= PG_vec;
table(Year',M_vec(final)',W_vec(final)', M_vec(final)'-W_vec(final)',ER_vec(final)', PG_vec','VariableNames',{Year, Average Male Salary', Average Womens Salary, Difference in Annual Salary, Earnings Ratio, Pay Gap});
Frank Maley
Frank Maley on 4 Nov 2019
How do I get final to change to a vector? I thought setting it to a (1:20) would work.

Sign in to comment.

Answers (1)

Roshni Garnayak
Roshni Garnayak on 7 Nov 2019
There are couple of things to note here:
  • M_vec(final)is of size 1x1 and contains only the last element of the vector M_vec. While creating the table you need to take the entire array, M_vec.
  • The variable names have to be enclosed in single quotes. Moreover, spaces are not allowed in variable names.
Make the following changes in the last line of your code:
table(Year',M_vec',W_vec', M_vec'-W_vec',ER_vec', PG_vec','VariableNames',{'Year', 'AverageMaleSalary', 'AverageWomensSalary', 'DifferenceInAnnualSalary', 'EarningsRatio', 'PayGap'});
  1 Comment
Steven Lord
Steven Lord on 7 Nov 2019
As of release R2019b, table and timetable variable names are allowed to contain spaces. See the Release Notes. If you are using an older release Roshni Garnayak is correct that you will need to remove the spaces from your table variable names.
Note that this applies to the names of variables in table and timetable arrays only. The names of "standalone" variables must satisfy the requirements stated in the documentation for the isvarname function.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!