Concatenation is done using square brackets []. Curly brackets are for defining cell arrays. Also, while it is a question of preference, we generally avoid defining variables for storing all field names and values. Instead, we use directly the strings and values in the call to STRUCT.
To illustrate:
function schedule = addGameStruct(hometeam, awayteam, homescore, awayscore, schedule)
%ADDGAMESTRUCT
% schedule is a structure with fields hometeam, awayteam, homescore,
% awayscore, and winner that holds the current data and will be expanded
% to include a new game
% hometeam: home team's final score
% awayscore: away team's final score
% - Set default empty array to schedule when not passed (init).
if nargin < 5
schedule = [] ;
end
% - Build data struct.
s = struct('hometeam', hometeam, 'awayteam', awayteam, 'homescore', homescore, ...
'awayscore', awayscore, 'winner', 'Cal') ;
% - Append data struct (concatenate) to schedule struct array.
schedule = [schedule; s] ;
end
Note that I pass schedule as last element and test whether something was passed. This allows to pass nothing when initializing the schedule with a first entry.
>> schedule = addGameStruct('A', 'B', 10, 5) ;
>> schedule = addGameStruct('C', 'D', 8, 12, schedule) ;
..
but this too is a question of personal preference. Finally, note that using STRUCT2TABLE is useful for displaying struct arrays (e.g. for debugging):
>> struct2table(schedule)
ans =
2×5 table
hometeam awayteam homescore awayscore winner
________ ________ _________ _________ ______
'A' 'B' 10 5 'Cal'
'C' 'D' 8 12 'Cal'
PS: and if once you want to extend this exercise with object oriented MATLAB, this is one way to do it: define a class Schedule saved in Schedule.m :
classdef Schedule < handle
properties
data
end
methods
function obj = Schedule(varargin)
obj.data = struct('hometeam', {}, 'awayteam', {}, 'homescore', [], ...
'awayscore', [], 'winner', {}) ;
if nargin
obj.add(varargin{:}) ;
end
end
function add(obj, hometeam, awayteam, homescore, awayscore)
dId = numel(obj.data) + 1 ;
obj.data(dId).hometeam = hometeam ;
obj.data(dId).awayteam = awayteam ;
obj.data(dId).homescore = homescore ;
obj.data(dId).awayscore = awayscore ;
obj.data(dId).winner = 'Cal' ;
end
function dispTable( obj )
disp(struct2table(obj.data)) ;
end
end
end
and then you can create an object and "talk" to it (no need to pass a struct array to a function that returns another struct array, as data and functions are grouped in the class:
>> schedule = Schedule() ;
>> schedule.add('A', 'B', 10, 5) ;
>> schedule.add('C', 'D', 8, 12) ;
or more concisely:
>> schedule = Schedule('A', 'B', 10, 5) ;
>> schedule.add('C', 'D', 8, 12) ;
and then
>> schedule.dispTable
hometeam awayteam homescore awayscore winner
________ ________ _________ _________ ______
'A' 'B' 10 5 'Cal'
'C' 'D' 8 12 'Cal'