index exceeds matrix dimensions help (new to matlab)

1 view (last 30 days)
Just started my first MATLAB class so I'm brand new to it. I am trying to make this table but i keep getting that error. I can not figure out how to fix it. Basically its a table with columns of year, model, mpg, and CO2 with me computing the CO2 from the given mpg. Theres 6 different cars so 6 rows. I put what it is suppose to look like below. Any help will be appreciated. Thank You.
year model mpg CO2
--------------------------------------------------------
2008 smart for two 37 mpg 6291.89 lbs
2008 civic coupe 29 mpg 8027.59 lbs
2008 civic hybrid 43 mpg 5413.95 lbs
2008 chevrolet cobalt 30 mpg 7760.00 lbs
2008 toyota prius (hybrid) 46 mpg 5060.87 lbs
2008 toyota yaris 32 mpg 7275.00 lbs
--------------------------------------------------------
mpg={'37 mpg', '29mpg', '43 mpg', '30 mpg', '46 mpg', '32 mpg'};
g=[37; 29; 43; 30; 46; 32];
y=2008;
c=(g.^(-1)*12000)*19.4;
k=(1:6);
car={'smart for two', 'civic coupe', 'civic hybrid', 'chevrolet cobalt', 'toyota prius (hybrid)', 'toyota yaris'};
fprintf('\n');
fprintf('year model mpg CO2\n');
fprintf('------------------------------------------\n');
for i=k+1,
fprintf('%4d %21s %s %4.2f\n', y(i), car{i}, mpg{i}, c(i));
end

Accepted Answer

Sean de Wolski
Sean de Wolski on 8 Sep 2011
k = 1:6
i.e. k = [1 2 3 4 5 6]
for i = k+1
translates to MATLAB as
for i = [2 3 4 5 6 7]
your matrices are only 6 elements long so when they try and print the 7th it says the index exceeds the dimension (i.e. car{7} doesn't exist because car is only 6 elements long)

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!