Trouble With Table And Graph (Real World Application of Loops and Branches)
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
clc
M=66097;
W=63554;
a=1:20;
M_vec= zeros(1,20);
W_vec= zeros(1,20);
ER=0;
PG=0;
ER_vec= zeros(1,20);
PG_vec= zeros(1,20);
format bank
for final = a
M=1.05*M;
M_vec(final)= M;
W=1.05*W;
W_vec(final)= W;
ER=M_vec/W_vec;
ER_vec(final)=ER;
PG_vec=(M_vec(final)-W_vec(final))/M_vec(final);
end
Year=(2018:1:2037);
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});
댓글 수: 2
Walter Roberson
2019년 11월 4일
After your for final loop, final will be a scalar so M_vec(final) will be a scalar. That has a different number of rows than does Year' which has 20 rows.
I think the table is supposed to include all of the M_vec values.
답변 (1개)
Roshni Garnayak
2019년 11월 7일
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
Steven Lord
2019년 11월 7일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!