每当列

时间:2017-12-29 18:57:07

标签: matlab matrix indexing

假设我有矩阵A:

A = [... %ID  Time   X
    1   0    0.7
    1   1    0.1
    1   2   -0.5
    1   3   -1.6
    3   0    0.3
    3   1    0.2
    3   2    0.0
    3   3   -0.2
    4   0    0.7
    4   1   -0.1
    4   2   -0.3
    4   3    0.2
    5   0   -0.5
    5   1   -0.4
    5   2   -0.9
    5   3   -0.4
    8   0    0.5
    8   1    1.0
    8   2    0.3
    8   3    0.4
    ];

你如何最终得到这样的东西(即矩阵B):

ID  Time      X
1     0      0.7
1     1      0.1
1     2     -0.5
1     3     -1.6
2   -999    -999
2   -999    -999
2   -999    -999
2   -999    -999
3     0      0.3
3     1      0.2
3     2      0.0
3     3     -0.2
4     0      0.7
4     1     -0.1
4     2     -0.3
4     3      0.2
5     0     -0.5
5     1     -0.4
5     2     -0.9
5     3     -0.4
6   -999    -999
6   -999    -999
6   -999    -999
6   -999    -999
7   -999    -999
7   -999    -999
7   -999    -999
7   -999    -999
8     0      0.5
8     1      1.0
8     2      0.3
8     3      0.4

如果'id'列中存在非连续的间隙,我想添加一个带有'-999s'的单独矩阵,并用适当的(即连续的)ID号标记'id'列。注意ID 5和ID 8之间有两个间隙 - 理想情况下,我可以填写缺失值两次并相应地标记它们(例如,ID 6和ID 7)。

我已尝试过以下代码,但未成功。请注意,“数据”是一个类似于上面的矩阵A的矩阵。 'filler'是-99s的3x4矩阵:

-999 -999 -999
-999 -999 -999
-999 -999 -999
-999 -999 -999

示例代码:

ii = 1; %Starting counter
kk = ii+4; %So I don't start by indexing a row which doesn't yet exist

for ii = 1:4:length(data);
    if data(kk,1) ~= data(kk-4,1) + 1; %If there's a gap between the ID values greater than 1, i.e. they are non-consecutive
        data = [data(1:kk-1, :); filler; data(kk:end, :)]; %Append the filler column to the part of the matrix where another ID should be
    elseif data(kk,1) == -999; 
        end
end

4 个答案:

答案 0 :(得分:2)

这里没有任何循环的解决方案(A是初始矩阵,B结果)。目前,假设ID值重复4次,而在2.列中,您的值为0:3。不确定它是否比Tommasos解决方案更快,因为ismember可能会花费大量时间用于非常大的矩阵。

% create template B to fill in values
B = [repelem(A(1,1):A(end,1),1,4).' repmat(0:3,1,A(end,1)-A(1,1)+1).' repmat(-999,(A(end,1)-A(1,1)+1)*4,1)];

% copy values from column 3 of A to column 3 of B where the first 2 columns are the same
[~,loc] = ismember(A(:,1:2),B(:,1:2),'rows');
B(loc,3) = A(:,3);

% Where column 3 == -999, also set column 2 to -999
B(B(:,3)==-999,2)=-999;

答案 1 :(得分:2)

accumarray的经典作业:

fillval = -999;
A = [...
    1   0    0.7
    1   1    0.1
    1   2   -0.5
    1   3   -1.6
    3   0    0.3
    3   1    0.2
    3   2    0.0
    3   3   -0.2
    4   0    0.7
    4   1   -0.1
    4   2   -0.3
    4   3    0.2
    5   0   -0.5
    5   1   -0.4
    5   2   -0.9
    5   3   -0.4
    8   0    0.5
    8   1    1.0
    8   2    0.3
    8   3    0.4
    ];

%// Compact solution
X = accumarray(A(:,1),(1:size(A,1)).',[],@(x) {A(x,:)});
X(cellfun(@isempty,X)) = {fillval*ones(size(X{1}))};
out = cell2mat(X);

说明:

% indices of groups
gidx = A(:,1);
% vector of all indices
N = 1:size(A,1);  
% create groups with accumarray
X = accumarray(gidx(:),N(:),[],@(x) {A(x,:)});
% create logical vector for missing indices
mask = cellfun(@isempty,X);
% form fill matrix with same size as single group
fillmat = fillval*ones(size(X{1}));
% expand A to complete matrix with fill values
X(mask) = {fillmat};
% transform cell array to double array
out = cell2mat(X);

答案 2 :(得分:1)

您可以更正以下内容:

result = zeros(4*max(data(:,1)),3); % initialization
last_idx = 1; % counter from 1 to max
idx = 1;
len = length(data(:,1));
while(idx < len)
    range = (4*(last_idx-1)+1):(4*last_idx);
    if data(idx,1) ~= last_idx % find missed index
        result(range,:) = repmat([last_idx -9 -9],4,1);
    else
        result(range,:) = data(idx:idx+3,:);
        idx = idx + 4;
    end
    last_idx = last_idx + 1;
end

答案 3 :(得分:1)

我建议您使用以下解决方案,其中我尝试尽可能地对该过程进行矢量化:

 1     0   0.7
 1     1   0.1
 1     2  -0.5
 1     3  -1.6
 2  -999  -999
 2  -999  -999
 2  -999  -999
 2  -999  -999
 3     0   0.3
 3     1   0.2
 3     2     0
 3     3  -0.2
 4     0   0.7
 4     1  -0.1
 4     2  -0.3
 4     3   0.2
 5     0  -0.5
 5     1  -0.4
 5     2  -0.9
 5     3  -0.4
 6  -999  -999
 6  -999  -999
 6  -999  -999
 6  -999  -999
 7  -999  -999
 7  -999  -999
 7  -999  -999
 7  -999  -999
 8     0   0.5
 8     1     1
 8     2   0.3
 8     3   0.4

结果:

B =

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Current Standings</title>
<style type="text/css">
body, td {
	font: 13px "Lucida Grande", "Lucida Sans Unicode", Tahoma, Verdana;
}
a, a:visited {
	border-bottom: 1px solid #69c;
	color: #00019b;
	text-decoration: none;
}
th {
	text-align: left;
}

.standingstable {
width: 760px;
}

.gamestable, .scorestable, .teamhistory {
border-collapse: collapse;
margin-top: 10px;
margin-bottom: 10px;
width: 700px;
}

.gamestable td, .gamestable th, .scorestable td, .scorestable th, .teamhistory td, .teamhistory th {
padding: 5px;
border: 1px solid black;
}

.gamestable tr, .scorestable tr, .teamhistory tr {
vertical-align: top;
}
</style>

</head>
<body>
<h2>Current Standings</h2>
<?php
require "settings.php";

if (isset($_GET['conf'])) {
    $confid = intval($_GET['conf']);
}
else {
    $confid = 0;
}
if (isset($_GET['team'])) {
    $team = intval($_GET['team']);
}
else {
    $team = 0;
}
if (isset($_GET['history'])) {
    $history = intval($_GET['history']);
}
else {
    $history = 0;
}

mysql_connect($sportsdb_host,$sportsdb_user,$sportsdb_pass);
@mysql_select_db($sportsdb_db) or die( "Unable to select database");

include 'standings_functions.php';

if ($history > 0) {
    // We need the team ID and the conference ID too
    if ($confid < 1 || $team < 1) {
        die ('Not enough information supplied');
    }
    print '<p><a href="?conf=' . $confid . '">Back to the conference standings</a></p>' . "\n";
    print '<p><a href="?conf=' . $confid . '&team=' . $team . '">Back to the team schedule</a></p>' . "\n";
    
    $query = 'SELECT teamname, masterteam FROM sportsdb_teams WHERE teamid = ' . $team . ' LIMIT 1';
    $result = mysql_query($query);
    if (mysql_num_rows($result) == 0) {
        die('No such team exists');
    }
    else {
        $teamname = mysql_result($result,0,"teamname");
        $masterteam = mysql_result($result,0,"masterteam");
    }
    print '<h3>' . $teamname . ' history</h3>' . "\n";
    $query = 'SELECT sportsdb_teams.teamid, sportsdb_teams.teamname, sportsdb_teams.teamwins, sportsdb_teams.teamlosses, sportsdb_teams.teamties, sportsdb_teams.teamforfeits, 
    sportsdb_divs.divname, 
    sportsdb_conferences.confname, sportsdb_conferences.confid,  
    sportsdb_seasons.seasonname 
    FROM sportsdb_teams, sportsdb_divs, sportsdb_conferences, sportsdb_seasons 
    WHERE sportsdb_teams.masterteam = ' . $masterteam . ' 
    AND sportsdb_teams.teamdiv = sportsdb_divs.divid 
    AND sportsdb_divs.conference = sportsdb_conferences.confid 
    AND sportsdb_conferences.season = sportsdb_seasons.seasonid 
    ORDER BY sportsdb_seasons.seasonorder';
    $result = mysql_query($query) or die ('Error in query: ' . $query);
?>
<table class="teamhistory">
    <tr>
        <th>Season</th>
        <th>Team</th>
        <th>Conference</th>
        <th>Division</th>
        <th>Wins</th>
        <th>Losses</th>
        <?php if ($show_ties) { ?><th>Ties</th><?php } ?>
        <?php if ($forfeits) { ?><th>Forfeits</th><?php } ?>
    </tr>
<?php
    while ($teams = mysql_fetch_array($result, MYSQL_ASSOC) ) {
        $seasonname = htmlspecialchars($teams['seasonname'], ENT_QUOTES);
        print "\t" . '<tr>' . "\n";
        print "\t\t" . '<td>' . $seasonname . '</td>' . "\n";
        print "\t\t" . '<td><a href="?team=' . $teams['teamid'] . '&conf=' . $teams['confid'] . '">' . $teams['teamname'] . '</td>' . "\n";
        print "\t\t" . '<td><a href="?conf=' . $teams['confid'] . '">' . $teams['confname'] . '</a></td>' . "\n";
        print "\t\t" . '<td>' . $teams['divname'] . '</td>' . "\n";
        print "\t\t" . '<td>' . $teams['teamwins'] . '</td>' . "\n";
        print "\t\t" . '<td>' . $teams['teamlosses'] . '</td>' . "\n";
        if ($show_ties) {
            print "\t\t" . '<td>' . $teams['teamties'] . '</td>' . "\n";
        }
        if ($forfeits) {
            print "\t\t" . '<td>' . $teams['teamforfeits'] . '</td>' . "\n";
        }
        print "\t" . '</tr>' . "\n";
    }
    print '</table>' . "\n";
}
elseif ($team > 0) {
    // We need the conference ID too
    if ($confid < 1) {
        die ('Not enough information supplied');
    }
    
    print '<p><a href="?conf=' . $confid . '">Back to the conference standings</a></p>' . "\n";
    print '<h3>' . get_team_name($team). ': full schedule and scores</h3>' . "\n";
    print '<p><a href="?history=1&team=' . $team . '&conf=' . $confid . '">Team history</a></p>' . "\n";
    sls_team_schedule($team);
}

elseif ($confid > 0) {

// Allow sorting to occur
if (isset($_GET['sort'])) {
    $standings_sort = intval($_GET['sort']);
}
else {
    $standings_sort = 0;
}
switch ($standings_sort) {
/*
Available sort fields:

Name: teamname
Wins: teamwins
Losses: teamlosses
Ties: teamties
Forfeits: teamforfeits
Runs for: teamrf
Runs against: teamra
Games behind: gamesbehind
Points: points
Winning percentage: winningpct
Custom tie break: teamorder

Separate the fields by commas and always specify a sort order as DESC for descending and ASC for ascending
*/
case 1: // Sort by team name
$sort_order = "teamname ASC"; break;
case 2: // Sort by wins
$sort_order = "teamwins DESC, teamties DESC, teamlosses ASC, teamorder DESC"; break;
case 3: // Sort by losses
$sort_order = "teamlosses DESC, teamwins ASC, teamties ASC, teamorder DESC"; break;
case 4: // Sort by ties
$sort_order = "teamties DESC, teamwins DESC, teamlosses ASC, teamorder DESC"; break;
case 5: // Sort by forfeits
$sort_order = "teamforfeits DESC, teamwins ASC, teamties ASC, teamorder DESC"; break;
case 6: // Sort by games played
$sort_order = "gamesplayed DESC, teamwins DESC, teamties DESC, teamlosses ASC, teamorder DESC"; break;
case 7: // Sort by runs for
$sort_order = "teamrf DESC, teamwins ASC, teamties DESC, teamlosses ASC, teamorder DESC"; break;
case 8: // Sort by runs against
$sort_order = "teamra DESC, teamwins DESC, teamties ASC, teamlosses DESC, teamorder DESC"; break;
case 9: // Sort by games behind
$sort_order = "gamesbehind ASC, teamties DESC, teamwins DESC, teamlosses ASC, teamorder DESC"; break;
case 10: // Sort by points
$sort_order = "points DESC, teamwins DESC, winningpct DESC, teamorder DESC"; break;
default: // Sort by winning percentage
$standings_sort = 0; $sort_order = "winningpct DESC, teamorder DESC";
}
$division_sort = "";

// Different winning percentage calculations
switch ($winning_pct_calc) {
    case 2: // Treating a tie as a half win
    $winning_pct_formula = '((teamwins + (teamties / 2)) / (teamwins + teamties + teamlosses + teamforfeits))';
    break;

    case 3: // Treating winning percentage as number of points relative to total possible points
    $winning_pct_formula = '((teamwins * ' . $points_win . ' + teamforfeits * ' . $points_forfeit . ' + teamties * ' . $points_tie . ') / ((teamwins + teamties + teamlosses + teamforfeits) * ' . $points_win . '))';
    break;
    
    default: // Ignoring ties
    $winning_pct_formula = '(teamwins / (teamwins + teamlosses + teamforfeits))';
}

// print the conference name
$resultconf = mysql_query("SELECT sportsdb_conferences.confname, sportsdb_seasons.seasonid, sportsdb_seasons.seasonname FROM sportsdb_conferences, sportsdb_seasons WHERE sportsdb_conferences.confid = $confid AND sportsdb_conferences.season = sportsdb_seasons.seasonid LIMIT 1");
$confname = @mysql_result($resultconf, 0, 'confname') or die ('No such conference');
$seasonid = mysql_result($resultconf, 0, 'seasonid');
$seasonname = mysql_result($resultconf, 0, 'seasonname');
$seasonname = htmlspecialchars($seasonname, ENT_QUOTES);

print '<h2>' . $confname . ' (' . $seasonname . ')</h2>' . "\n";
print '<p><a href="' . $_SERVER['PHP_SELF'] . '?season=' . $seasonid . '">Back to conference list</a></p>';
print "\n" . '<hr />' . "\n";

// Get the divisions

$resultconf = mysql_query("SELECT divname, divid FROM sportsdb_divs WHERE conference = $confid ORDER BY divorder");
$numconf = mysql_num_rows($resultconf);
if ($numconf == 0) {
print "<p>No divisions in this conference</p>\n";
}

else {
while ($divs = mysql_fetch_array($resultconf, MYSQL_ASSOC)) {

// Loop through each division

$divname = $divs['divname'];
?>

<h3><?php print $divname; ?></h3>
<table class="standingstable">
    <tr>
        <td width="25%"><?php if ($standings_sort != 1) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=1\">"; ?><strong>Team Name</strong><?php if ($standings_sort != 1) print '</a>'; ?></td>
        <td><?php if ($standings_sort != 6) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=6\">"; ?><strong>GP</strong><?php if ($standings_sort != 2) print '</a>'; ?></td>
        <td><?php if ($standings_sort != 2) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=2\">"; ?><strong>Wins</strong><?php if ($standings_sort != 2) print '</a>'; ?></td>
        <td><?php if ($standings_sort != 3) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=3\">"; ?><strong>Losses</strong><?php if ($standings_sort != 3) print '</a>'; ?></td>
<?php if ($show_ties) { ?>
        <td><?php if ($standings_sort != 4) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=4\">"; ?><strong>Ties</strong><?php if ($standings_sort != 4) print '</a>'; ?></td>
<?php } ?>
<?php if ($forfeit) { ?>
        <td><?php if ($standings_sort != 5) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=5\">"; ?><strong>Forfeits</strong><?php if ($standings_sort != 5) print '</a>'; ?></td>
<?php } ?>
<?php if ($show_rfra) { ?>
        <td><?php if ($standings_sort != 7) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=7\">"; ?><strong>RF</strong><?php if ($standings_sort != 7) print '</a>'; ?></td>
        <td><?php if ($standings_sort != 8) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=8\">"; ?><strong>RA</strong><?php if ($standings_sort != 8) print '</a>'; ?></td>
<?php } ?>
<?php if ($show_gb) { ?>
        <td><?php if ($standings_sort != 9) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=9\">"; ?><strong>GB</strong><?php if ($standings_sort != 9) print '</a>'; ?></td>
<?php } ?>
        <td><?php if ($standings_sort != 0) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=0\">"; ?><strong>PCT</strong><?php if ($standings_sort != 0) print '</a>'; ?></td>
<?php if ($show_points) { ?>
        <td><?php if ($standings_sort != 10) print '<a href="' . $_SERVER['PHP_SELF'] . "?conf=$confid&sort=10\">"; ?><strong>Points</strong><?php if ($standings_sort != 10) print '</a>'; ?></td>
<?php } ?>
    </tr>

<?php
$query = "SELECT COUNT(*) FROM sportsdb_teams WHERE teamdiv = {$divs['divid']}";
$result = mysql_query($query);
$result_exist = mysql_result($result,0);

if ($result_exist) {
    $query = "SELECT teamid, teamname, teamwins, teamties, teamlosses, teamforfeits, teamrf, teamra, 
    (teamwins + teamties + teamlosses + teamforfeits) AS gamesplayed, 
    (teamwins * $points_win + teamforfeits * $points_forfeit + teamties * $points_tie) AS points, 
    $winning_pct_formula AS winningpct, 
    (teamwins - teamlosses - teamforfeits) AS leadervalue 
    FROM sportsdb_teams 
    WHERE teamdiv = {$divs['divid']} 
    ORDER BY leadervalue DESC, teamties DESC LIMIT 1";
    
    $result = mysql_query($query) or die ("Error in query: $query");
    $results = mysql_fetch_array($result, MYSQL_ASSOC);
    $winningpct = number_format($results['winningpct'], 3);
}

// Show the leader at the top for default sorting (games behind)

if ($standings_sort == 9) {
?>
    <tr>
        <td><a href="?conf=<?php print $confid; ?>&team=<?php print $results['teamid']; ?>" title="View scores for <?php print $results['teamname']; ?>"><em><?php print $results['teamname']; ?></em></a></td>
        <td><?php print $results['gamesplayed']; ?></td>
        <td><?php print $results['teamwins']; ?></td>
        <td><?php print $results['teamlosses']; ?></td>
<?php if ($show_ties) { ?>
        <td><?php print $results['teamties']; ?></td>
<?php }
if ($forfeit) { ?>
        <td><?php print $results['teamforfeits']; ?></td>
<?php }
if ($show_rfra) { ?>
        <td><?php print $results['teamrf'];?></td>
        <td><?php print $results['teamra'];?></td>
<?php }
if ($show_gb) { ?>
        <td>---</td>
<?php } ?>
        <td><?php print $winningpct; ?></td>
<?php if ($show_points) { ?>
        <td><?php print $results['points'] ?></td>
<?php } ?>
    </tr>
<?php }

if ($result_exist) {
        $query="SELECT teamid, teamname, teamwins, teamties, teamlosses, teamforfeits, teamrf, teamra, 
        (teamwins + teamties + teamlosses + teamforfeits) AS gamesplayed, 
        (teamwins * $points_win + teamforfeits * $points_forfeit + teamties * $points_tie) AS points, 
        $winning_pct_formula AS winningpct, 
        ((({$results['leadervalue']}) - (teamwins - teamlosses - teamforfeits)) / 2) AS gamesbehind 
        FROM sportsdb_teams 
        WHERE teamdiv = {$divs['divid']}";

        if ($standings_sort == 9) {
            $query .= " AND teamid != {$results['teamid']}";
        }
        $query .= " AND active = 1" . $division_sort . " ORDER BY $sort_order";

        $result=mysql_query($query);
        $num=mysql_num_rows($result);

        while ($results = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $winningpct=number_format($results['winningpct'], 3);
            $gamesbehind = number_format($results['gamesbehind'],1);

            if ($gamesbehind == "0.0") {
                $gamesbehind = "---";
            }
?>
    <tr>
        <td><a href="?conf=<?php print $confid; ?>&team=<?php print $results['teamid']; ?>" title="View scores for <?php print $results['teamname']; ?>"><em><?php print $results['teamname']; ?></em></a></td>
        <td><?php print $results['gamesplayed']; ?></td>
        <td><?php print $results['teamwins']; ?></td>
        <td><?php print $results['teamlosses']; ?></td>
<?php if ($show_ties) { ?>
        <td><?php print $results['teamties']; ?></td>
<?php }
if ($forfeit) { ?>
        <td><?php print $results['teamforfeits']; ?></td>
<?php }
if ($show_rfra) { ?>
        <td><?php print $results['teamrf']; ?></td>
        <td><?php print $results['teamra']; ?></td>
<?php }
if ($show_gb) { ?>
        <td><?php print $gamesbehind; ?></td>
<?php } ?>
        <td><?php print $winningpct; ?></td>
<?php if ($show_points) { ?>
        <td><?php print $results['points']; ?></td>
<?php } ?>
    </tr>
<?php
        }
    }
?>
</table>
<?php } ?>

<a name="pastscores"></a><h2>Past Scores</h2>

<form name="teamsort" method="post" action="<?php print $_SERVER['REQUEST_URI']; ?>#pastscores">
<p>
    Show only 
    <select name="teamtosort">
        <option value="all">All teams</option>
<?php
// Populate the list of teams
$queryteams = "SELECT sportsdb_teams.teamname, sportsdb_teams.teamid 
            FROM sportsdb_teams, sportsdb_divs 
            WHERE sportsdb_teams.teamdiv = sportsdb_divs.divid 
            AND sportsdb_divs.conference = $confid 
            ORDER BY teamname";
            
$resultteams=mysql_query($queryteams);
$numteams=mysql_num_rows($resultteams);

while ($teams = mysql_fetch_array($resultteams, MYSQL_ASSOC)) {
    print "\t" . '<option value="' . $teams['teamid'] . '"';
    if ($teams['teamid'] == $_POST['teamtosort']) { 
        print ' selected="selected"';
    }
    print '>' . $teams['teamname'] . "</option>\n";
}
?>
    </select>
    <input type="submit" value="Go" />
</p>
</form>

<table class="scorestable">
    <tr>
        <th>Date</th>
        <th>Time</th>
        <th>Home</th>
        <th>Away</th>
<?php if ($show_fields) { ?>
        <th>Field</th>
<?php } ?>
        <th>Score</th>
        <th>&nbsp;</th>
    </tr>
<?php
$queryscores="SELECT sportsdb_wins.winid, sportsdb_wins.windate, sportsdb_wins.wintime, sportsdb_wins.rf, sportsdb_wins.ra, sportsdb_wins.winner,
    sportsdb_wins.loser, sportsdb_wins.wincomments, sportsdb_wins.field, sportsdb_wins.winortie, sportsdb_teams2.teamname AS winningteam,
    sportsdb_teams.teamname AS losingteam
    FROM sportsdb_wins
    LEFT JOIN sportsdb_teams ON sportsdb_wins.loser = sportsdb_teams.teamid
    LEFT JOIN sportsdb_teams AS sportsdb_teams2 ON sportsdb_wins.winner = sportsdb_teams2.teamid
    LEFT JOIN sportsdb_divs ON sportsdb_teams.teamdiv = sportsdb_divs.divid
    LEFT JOIN sportsdb_divs AS sportsdb_divs2 ON sportsdb_teams2.teamdiv = sportsdb_divs2.divid
    WHERE (sportsdb_divs.conference = $confid OR sportsdb_divs2.conference = $confid OR (sportsdb_wins.winconf = $confid AND (sportsdb_wins.loser = -1 OR sportsdb_wins.winner = -1))) AND sportsdb_wins.winortie != 3";

// Sort by team if specified
if (isset($_POST['teamtosort']) && $_POST['teamtosort'] != 'all') {
    $teamtosort = intval($_POST['teamtosort']);
    $queryscores .= " AND (sportsdb_wins.winner = $teamtosort OR sportsdb_wins.loser = $teamtosort)";
}

$queryscores .= ' ORDER BY wintime DESC';
$resultscores=mysql_query($queryscores);
$numscores=mysql_num_rows($resultscores);

while ($scores = mysql_fetch_array($resultscores, MYSQL_ASSOC)) {

    $windateheader=$scores['windate'];
    $windateformatted=date("F d, Y",$windateheader);
    $wintime=$scores['wintime'];
    $hour=date('g',$wintime);
    $minute=date('i',$wintime);
    $ampm=date('a',$wintime);
?>
    <tr>
        <td><?php print $windateformatted; ?></td>
        <td><?php print $hour . ':' . $minute . $ampm; ?></td>
        <td><?php print $scores['winningteam']; ?></td>
        <td><?php print $scores['losingteam']; ?></td>
<?php if ($show_fields) { ?>
        <td><?php print $scores['field']; ?></td>
<?php } ?>
        <td><?php print $scores['rf'] . ' - ' . $scores['ra'];
    if ($scores['winortie'] == 2 || $scores['winortie'] == 5) {
        print ' (ff)';
    }
    print '</td>';
?>

        <td><?php print $scores['wincomments']; ?></td>
    </tr>
<?php } ?>
</table>

<a name="upcominggames"></a><h2>Upcoming Games</h2>
<form name="teamsort" method="post" action="<?php print $_SERVER['REQUEST_URI']; ?>#upcominggames">
<p>Show only 
    <select name="teamtosort">
        <option value="all">All teams</option>
<?php
$queryteams = "SELECT sportsdb_teams.teamname, sportsdb_teams.teamid 
            FROM sportsdb_teams, sportsdb_divs 
            WHERE sportsdb_teams.teamdiv = sportsdb_divs.divid 
            AND sportsdb_divs.conference = $confid 
            ORDER BY teamname";
$resultteams=mysql_query($queryteams);
$numteams=mysql_num_rows($resultteams);

while ($teams = mysql_fetch_array($resultteams, MYSQL_ASSOC)) {
    print "\t" . '<option value="' . $teams['teamid'] . '"';
    if ($teams['teamid'] == $_POST['teamtosort']) {
        print ' selected';
    }
    print '>' . $teams['teamname'] . "</option>\n";
}
?>
    </select>
    <input type="submit" value="Go" />
</p>
</form>

<table class="gamestable">
    <tr>
        <th>Date</th>
        <th>Time</th>
        <th>Home</th>
        <th>Away</th>
<?php if ($show_fields) { ?>
        <th>Field</th>
<?php } ?>
        <th>&nbsp;</th>
    </tr>
<?php
$queryscores = "SELECT sportsdb_wins.winid, sportsdb_wins.windate, sportsdb_wins.wintime, sportsdb_wins.winner, sportsdb_wins.loser, 
    sportsdb_wins.wincomments, sportsdb_wins.field, sportsdb_teams2.teamname AS winningteam, sportsdb_teams.teamname AS losingteam
    FROM sportsdb_wins
    LEFT JOIN sportsdb_teams ON sportsdb_wins.loser = sportsdb_teams.teamid
    LEFT JOIN sportsdb_teams AS sportsdb_teams2 ON sportsdb_wins.winner = sportsdb_teams2.teamid
    LEFT JOIN sportsdb_divs ON sportsdb_teams.teamdiv = sportsdb_divs.divid
    LEFT JOIN sportsdb_divs AS sportsdb_divs2 ON sportsdb_teams2.teamdiv = sportsdb_divs2.divid
    WHERE (sportsdb_divs.conference = $confid OR sportsdb_divs2.conference = $confid OR (sportsdb_wins.winconf = $confid AND (sportsdb_wins.loser = -1 OR sportsdb_wins.winner = -1))) AND sportsdb_wins.winortie = 3";

// Sort by team if specified
if (isset($_POST['teamtosort']) && $_POST['teamtosort'] != 'all') {
        $teamtosort = intval($_POST['teamtosort']);
        $queryscores .= " AND (sportsdb_wins.winner = $teamtosort OR sportsdb_wins.loser = $teamtosort)";
}

$queryscores .= ' ORDER BY wintime ASC';
$resultscores = mysql_query($queryscores);
$numscores = mysql_num_rows($resultscores);

while ($scores = mysql_fetch_array($resultscores, MYSQL_ASSOC)) {

    $windateheader=$scores['windate'];
    $windateformatted=date("F d, Y",$windateheader);
    $wintime=$scores['wintime'];
    $hour=date('g',$wintime);
    $minute=date('i',$wintime);
    $ampm=date('a',$wintime);
?>
    <tr>
        <td><?php print $windateformatted; ?></td>
        <td><?php print $hour . ':' . $minute . $ampm; ?></td>
        <td><?php print $scores['winningteam']; ?></td>
        <td><?php print $scores['losingteam']; ?></td>
<?php if ($show_fields) { ?>
        <td><?php print $scores['field']; ?></td>
<?php } ?>
        <td><?php print $scores['wincomments'] ?></td>
    </tr>
<?php
        }
?>
</table>
<?php
    }
}

// List the conference in a specified season

elseif (($show_season || isset($_GET['season'])) && !isset($_GET['seasons']) ) {
    if (!$show_season || isset($_GET['season']) ) {
        $show_season = intval($_GET['season']);
    }
    $query = 'SELECT seasonname FROM sportsdb_seasons WHERE seasonid = ' . $show_season . ' LIMIT 1';
    $result = mysql_query($query) or die('Error in query ' . $query);
    if (mysql_num_rows($result) == 0) {
        die ('There is no such season.');
    }
    $seasonname = mysql_result($result,0);
    $seasonname = htmlspecialchars($seasonname, ENT_QUOTES);
    print '<p><a href="' . $_SERVER['PHP_SELF'] . '?seasons">Click here to view a list of seasons</a></p>' . "\n";
    print '<h3>' . $seasonname . ' season</h3>' . "\n";
?>
<p>Click on a conference name to view its standings</p>
<?php
    $query = "SELECT * FROM sportsdb_conferences WHERE season = $show_season ORDER BY conforder";
    $result = mysql_query($query) or die('Error in query ' . $query);
    $num = mysql_num_rows($result);
    while ($confs = mysql_fetch_array($result, MYSQL_ASSOC)) {
        print '<p><a href="' . $_SERVER['PHP_SELF'] . "?conf={$confs['confid']}\">{$confs['confname']}</a></p>\n";
    }
}
else {
?>
<p>Click on a season name to view its conferences</p>
<?php
    // List the seasons
    $query = 'SELECT * FROM sportsdb_seasons ORDER BY seasonorder';
    $result = mysql_query($query) or die('Error in query ' . $query);
    $num = mysql_num_rows($result);
    while ($seasons = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $seasonname = htmlspecialchars($seasons['seasonname'], ENT_QUOTES);
        print '<p><a href="' . $_SERVER['PHP_SELF'] . "?season={$seasons['seasonid']}\">$seasonname</a></p>\n";
    }
}
?>
</body>
</html>