Main Content

Calculate Win Percentage Using Python Dictionary Data

Supported platforms: Windows®, Linux®, Mac

This example shows how to create a Python® application that passes statistical data stored in a dictionary between Python and MATLAB®. The MATLAB function calculates a sports team's win percentage from its wins, losses, and ties. The Python application creates the dictionary data, calls the MATLAB function, and displays the results. When you pass data between MATLAB and Python, the data is converted into an equivalent data type. For a complete list of data types and their conversions, see Pass Data Between MATLAB and Python.

Prerequisites

Verify that you have a version of Python installed that is compatible with MATLAB Compiler SDK™. For details, see MATLAB Compiler SDK Python Target Requirements.

The target machine requires MATLAB Runtime to run the deployed MATLAB code. You can include MATLAB Runtime in an installer for your Python package or install it separately. For details, see Download and Install MATLAB Runtime.

Create Function in MATLAB

Write a MATLAB function named insertWinPercentage that accesses data stored in a dictionary object.

function outputArg = insertWinPercentage(stats)
% Check if the necessary keys exist
if isKey(stats, "Wins") && isKey(stats, "Losses") && isKey(stats, "Ties")
    % Calculate the win percentage
    wins = stats("Wins");
    gamesPlayed = wins + stats("Losses") + stats("Ties");
    winPercent = (wins / gamesPlayed) * 100;
    
    % Add the win percentage to the dictionary
    stats("WinPercentage") = round(winPercent,2);
else
    % The necessary data is not available
    disp("Required data (Wins, Losses, and/or Ties) is missing from the dictionary.");
end

outputArg = stats;
end

In this example, the function takes a dictionary object stats that contains statistics, calculates and adds a win percentage entry, and outputs the modified dictionary object.

Create Python Package

Build the Python package with the Library Compiler app or the compiler.build.pythonPackage function. Compile using the insertWinPercentage.m file and name the package accessDict.

For example, if you are using compiler.build.pythonPackage, type:

buildResults = compiler.build.pythonPackage( ...
'insertWinPercentage.m', ...
'PackageName','accessDict');

For details, see the instructions in Generate Python Package and Build Python Application.

Write Python Application Code

Write code in Python for an application named modifyDict that calls the MATLAB function. This sample application displays the dictionary data before and after modification.

#!/usr/bin/env python
"""
Sample that uses the accessDict package you created using
MATLAB Compiler SDK. See the MATLAB Compiler SDK 
documentation for more information.
"""
import accessDict

# Import the matlab package only after you have imported 
# all MATLAB Compiler SDK generated Python packages.

import matlab

try:
    myaccessDict = accessDict.initialize()    
except Exception as e:
    print('Error initializing accessDict package\n:{}'.format(e))
    exit(1)
try:
    # Function to print the dictionary keys and values
    def print_dictionary(dct):    
        for key, val in dct.items():
            print("{} ({})".format(key, val))
    
    # Define keys and values for the dictionary    
    stats = {    
        'Wins': float(24),
        'Losses': float(8),
        'Ties': float(2),
        'AveragePoints': float(110.5),
        'HighestPointTotal': float(152)}
    
    # Convert stats to a matlab.dictionary, which is automatically
    # converted to a MATLAB dictionary when passed to MATLAB.
    m_stats = matlab.dictionary(stats)    
    
    #Print dictionary before and after modification
    print('Without win percentage:')
    print_dictionary(m_stats)

    newstats = myaccessDict.insertWinPercentage(m_stats)

    print('\nWith win percentage:')
    print_dictionary(newstats)

except Exception as e:
    print('Error occurred during program execution\n:{}'.format(e))
myaccessDict.terminate()

The application does the following:

  • Imports the accessDict and matlab packages.

  • Instantiates the accessDict instance as myaccessDict.

  • Saves the data in a matlab.dictionary object named stats.

  • Calls the insertWinPercentage method in the accessDict package to create a modified copy of the dictionary named newstats.

  • Displays the contents of stats and newstats using the helper function print_dictionary.

  • Uses a try block to catch and handle any exceptions.

Install and Run Python Package

On the target machine, install the generated Python package. For more details, see Install and Import MATLAB Compiler SDK Python Packages.

In the system command prompt, navigate to the folder containing the generated files and install the Python package.

python -m pip install .

Run the application.

python modifyDict.py

The application generates the following output.

Without win percentage: 
Wins (24.0) 
Losses (8.0) 
Ties (2.0) 
AveragePoints (110.5) 
HighestPointTotal (152.0) 
 
With win percentage: 
Wins (24.0) 
Losses (8.0) 
Ties (2.0) 
AveragePoints (110.5) 
HighestPointTotal (152.0) 
WinPercentage (70.59) 

See Also

|

Related Topics