MATLAB Answers

Martin
0

Can this stacking code be simplified

Asked by Martin
on 27 Aug 2019
Hello,
I need to create a figure (f) and insert a table. It works well:
f = figure('units','normalized');
pets = table({'22:00'},4,6,'VariableNames',{'Time','Dogs','Cats'})
uit = uitable(f);
uit.Data = {'Time','Dogs','Cats'; char(pets.Time(end)),num2str(pets.Dogs(end)),num2str(pets.Cats(end)) };
But in this case there are only 1 row in the pets table (which can happen in my code). The problem arrive when more rows exist in the table since I only need to show the last 7 rows. If there are fewer than 7 rows I need to show those.
Until now I got the following which works:
if size(pets,1) == 1
uit.Data = {'Time','Dogs','Cats'; char(pets.Time(end)),num2str(pets.Dogs(end)),num2str(pets.Cats(end)) };
elseif size(pets,1) == 2
uit.Data = {'Time','Dogs','Cats'; char(pets.Time(end-1)),num2str(pets.Dogs(end-1)),num2str(pets.Cats(end-1)) ;...
char(pets.Time(end)),num2str(pets.Dogs(end)),num2str(pets.Cats(end)) };
elseif size(pets,1) == 3
uit.Data = {'Time','Dogs','Cats'; char(pets.Time(end-2)),num2str(pets.Dogs(end-2)),num2str(pets.Cats(end-2)) ;...
char(pets.Time(end-1)),num2str(pets.Dogs(end-1)),num2str(pets.Cats(end-1)) ;...
char(pets.Time(end)),num2str(pets.Dogs(end)),num2str(pets.Cats(end)) };
elseif ..... % 7 times
I do that 7 times, but that is a lot of code! Anyone have a way around this?

  0 Comments

Sign in to comment.

0 Answers