Variables: set characteristics (weight, colour) for different objects without having to do all manually

2 views (last 30 days)

I have a list of football teams, and certain characteristics about them, such as how many goals they have scored at home and away, how many corners they're had etc. So, say, "ARS.hs = number of goals scored at home for Arsenal" and "ARS.hc = number of goals conceded at home for Arsenal". I know how to do this for a particular team, and then copy and paste for the others, but is there a quicker way to do it for all 20 teams at the same time? Do I have to use something called structures?

Answers (2)

Image Analyst
Image Analyst on 26 Oct 2018
Yes, a structure array is fine. Just initialize one of them and then you can assign the very last one and it will automatically create all the in between ones:
% Initialize
ARS.goalsScored = 0;
ARS.gamesConceded = 1;
% Make an array of 20 of them.
ARS(20).gamesConceded = 0
ARS =
1×20 struct array with fields:
goalsScored
gamesConceded
I'd also advise you to use more descriptive variable names than you did. See what I picked.
By the way, this "trick" works with other variables too, like for double matrices:
m = rand(2,2) % Initialize it to 2x2.
m(10,5) = 0 % Grow it to 10 by 5

Steven Lord
Steven Lord on 26 Oct 2018
Depending on how your data is stored and what you want to do with the data, using a table instead of a struct may be easier to create and manipulate.
As an example, if I copy a subset of the data from the first couple rows of the current English Premier League table to a text file I can import it into MATLAB as a table. I used the Import Data tool on the Home tab of the toolstrip, which can also generate code if you have a lot of files that are imported the same way, but you could (depending on how the text file is formatted) use readtable.
I did have to tweak the file a bit; copying from a webpage to a text file left the formatting a bit odd. Copying from Wikipedia to the text file would probably be a bit easier, since the formatting in Wikipedia is probably simpler.
premierLeagueTable =
5×9 table
position club played won drawn lost GF GA GD
________ ___________________ ______ ___ _____ ____ __ __ __
1 "Manchester City" 9 7 2 0 26 3 23
2 "Liverpool" 9 7 2 0 16 3 13
3 "Chelsea" 9 6 3 0 20 7 13
4 "Arsenal" 9 7 0 2 22 11 11
5 "Tottenham Hotspur" 9 7 0 2 16 7 9
If I wanted to add a new variable to the table, that's easy.
premierLeagueTable.points = 3*premierLeagueTable.won + 1*premierLeagueTable.drawn
As long as the data has the same height as the table you can add it to the table. In the case above, since the won and drawn variables are part of the table they are obviously of the correct height.

Categories

Find more on Tables in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!