<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Schoepfloeffel on Medium]]></title>
        <description><![CDATA[Stories by Schoepfloeffel on Medium]]></description>
        <link>https://medium.com/@schoepfloeffel?source=rss-c52c7ebcf20a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l0bRPARGGqYXOV6U1hz5yA.png</url>
            <title>Stories by Schoepfloeffel on Medium</title>
            <link>https://medium.com/@schoepfloeffel?source=rss-c52c7ebcf20a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:49:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@schoepfloeffel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Going Against the Odds: Can You Really Beat the Bookies? The Guide to Football Sports Betting.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-061ea928d48a?source=rss-c52c7ebcf20a------2"><img src="https://cdn-images-1.medium.com/max/1024/1*kqgOwJZH1L2HpXsURUDLdQ.png" width="1024"></a></p><p class="medium-feed-snippet">Chapter 3: No Free Lunch. How to make money on bookies risk-management.</p><p class="medium-feed-link"><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-061ea928d48a?source=rss-c52c7ebcf20a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-061ea928d48a?source=rss-c52c7ebcf20a------2</link>
            <guid isPermaLink="false">https://medium.com/p/061ea928d48a</guid>
            <category><![CDATA[football-betting]]></category>
            <category><![CDATA[betting]]></category>
            <dc:creator><![CDATA[Schoepfloeffel]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 16:47:35 GMT</pubDate>
            <atom:updated>2024-08-01T16:47:35.320Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Going Against the Odds: Can You Really Beat the Bookies? The Guide to Football Sports Betting.]]></title>
            <link>https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-2d46a9c207bb?source=rss-c52c7ebcf20a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d46a9c207bb</guid>
            <category><![CDATA[betting]]></category>
            <category><![CDATA[football-betting]]></category>
            <dc:creator><![CDATA[Schoepfloeffel]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 16:46:58 GMT</pubDate>
            <atom:updated>2024-08-01T16:46:58.698Z</atom:updated>
            <content:encoded><![CDATA[<h4>Chapter 2 Add-on: Control question. Calculating the minimum bet to make the Bookmaker unprofitable (in the worst case).</h4><blockquote>”You don’t make money by predicting the outcome; you make money by understanding the market’s overall dynamics.”</blockquote><p>A trilogy about sports betting.</p><p><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-d3c2123e920c"><strong>Chapter 1: Understanding the Odds in Sports Betting.</strong></a></p><p><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-20244ea1d73a"><strong>Chapter 2: The Odds &amp; Probability Dilemma. How do bookies make money?</strong></a></p><p><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-061ea928d48a"><strong>Chapter 3: No Free Lunch. How to make money on bookies risk-management.</strong></a></p><p>This is an add-on to our three-part series on beating the booking which contains an exercise for Chapter 2 in calculating odds shifting in a ‘balanced market’.</p><blockquote><strong><em>Question</em></strong><em>: Determine the minimum amount ($) that needs to be bet on an ‘Away Win’ for the bookmaker to potentially incur a loss in the event of an ‘Away Win’.</em></blockquote><p><strong>Given Data:</strong></p><ul><li>Total liquidity (L) of the event: $10,000</li></ul><p>Odds provided for the outcomes on a 1X2 market:</p><ul><li>Home Win: 1.860</li><li>Draw: 3.646</li><li>Away Win: 3.794</li><li>The odds are assumed to be in equilibrium, meaning each outcome’s occurrence would result in the same financial outcome for the bookmaker.</li></ul><p><strong>Solution Approach:</strong></p><ol><li><strong><em>Calculating the Bookmaker’s Margin</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/0*KJ-y9q1P5sxqkrrO" /></figure><p><strong><em>2. Transforming Margin to Expected Payout</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/0*Pi2LCb7Yzptqdtqn" /></figure><p>This results in an expected payout for the bookmaker of approximately 7%.</p><p><strong><em>3. Adjusting for ‘Fair’ Odds</em></strong><em>: Removing the margin to find the fair odds</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*OaLLahSgxtlgdZVt" /></figure><p><strong><em>4. Stakes Distribution in Equilibrium</em></strong><em>: Assuming an equitable distribution of stakes in line with the fair odds:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*QJtoYPXHe8WijtM4" /></figure><p><strong><em>5. Calculating the Minimum Bet B for an ‘Away Win’ to make the bookmaker unprofitable (in the worst case scenario)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/0*SwiRqc0eRsvNzdsW" /></figure><blockquote>Solving this inequality for B yields a minimum bet of at least $250.54.</blockquote><p><strong><em>Shortcut Formula for Calculating B:</em></strong></p><p>Utilizing the shortcut based on the expected payout and adjusted odds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/0*a_WLKxYQypxUijUW" /></figure><p>The exercise highlights the critical threshold a bet must exceed to potentially shift the bookmaker’s financial exposure to a degree of unprofitableness, emphasizing the strategic nature of betting and odds setting in sports wagering markets. Bookmakers might employ hedging strategies with other market participants to have less risk-exposure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d46a9c207bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Against the Odds: Can You Really Beat the Bookies? The Guide to Football Sports Betting.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-20244ea1d73a?source=rss-c52c7ebcf20a------2"><img src="https://cdn-images-1.medium.com/max/1024/1*O4DyVbGiOmOeLxKbhQMqQQ.png" width="1024"></a></p><p class="medium-feed-snippet">Chapter 2: The Odds &amp; Probability Dilemma. How do bookies make money?</p><p class="medium-feed-link"><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-20244ea1d73a?source=rss-c52c7ebcf20a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-20244ea1d73a?source=rss-c52c7ebcf20a------2</link>
            <guid isPermaLink="false">https://medium.com/p/20244ea1d73a</guid>
            <category><![CDATA[betting]]></category>
            <category><![CDATA[football-betting]]></category>
            <dc:creator><![CDATA[Schoepfloeffel]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 16:46:25 GMT</pubDate>
            <atom:updated>2024-08-01T16:46:25.959Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Going Against the Odds: Can You Really Beat the Bookies? The Guide to Football Sports Betting.]]></title>
            <link>https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-d3c2123e920c?source=rss-c52c7ebcf20a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3c2123e920c</guid>
            <category><![CDATA[betting]]></category>
            <category><![CDATA[football-betting]]></category>
            <category><![CDATA[betting-strategies]]></category>
            <dc:creator><![CDATA[Schoepfloeffel]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 18:23:03 GMT</pubDate>
            <atom:updated>2024-07-29T18:23:03.807Z</atom:updated>
            <content:encoded><![CDATA[<h4>Chapter 1: Understanding the Odds in Sports Betting</h4><blockquote>”You don’t make money by predicting the outcome; you make money by understanding the market’s overall dynamics.”</blockquote><p>A trilogy about sports betting.</p><p><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-d3c2123e920c"><strong>Chapter 1: Understanding the Odds in Sports Betting.</strong></a></p><p><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-20244ea1d73a"><strong>Chapter 2: The Odds &amp; Probability Dilemma. How do bookies make money?</strong></a></p><p><a href="https://medium.com/@schoepfloeffel/going-against-the-odds-can-you-really-beat-the-bookies-the-guide-to-football-sports-betting-061ea928d48a"><strong>Chapter 3: No Free Lunch. How to make money on bookies risk-management.</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k22tJsWsy_dTCsDskOrSTw.png" /><figcaption><em>DALL-E</em>, version 3, OpenAI, 05Feb. 2024, labs.openai.com/</figcaption></figure><p>For data exploration, I have uploaded the dataset to <a href="https://www.kaggle.com/datasets/georgpolownikow/football-odds-and-players-german-leagues">Kaggle</a> and provided some useful tools on my <a href="https://github.com/Schoepfloeffel/SportsbettingMedium">GitHub</a>. Feel free to examine various bookmakers, markets, match statistics. I look forward to seeing any insights you might share.</p><p>Navigating the world of professional betting is challenging. Only a small fraction, less than 5% of bettors, manage to turn a profit, relying on discipline, analytical skills, and an emotionless approach to betting. Intrigued by the blend of entertainment and the inherent disadvantage faced by casual bettors, I dug into the mathematics of betting. I aimed to discover whether it is feasible for an individual to consistently make money in the long run or if the odds are overwhelmingly stacked in favour of bookmakers, leading to inevitable losses over time.</p><p>Historical accounts suggest that some have successfully beaten the odds through betting, yet today’s market is more informed and connected, altering the landscape significantly. While there are experts who claim to have winning formulas and share their strategies, my own experience with a sizable bankroll yielded profits for only eight months (and many matches involved). The success tapered off once I stopped actively monitoring my strategy. Although I prefer to keep the specifics of my system confidential, I am keen to share the insights I gained and what I would change if I were to do it again.</p><p>First, we need to understand the core of the sports betting market:</p><blockquote><strong>What are (the) odds?</strong></blockquote><p>Understanding basic concepts is crucial for laying the foundation to comprehend both — <strong>our odds</strong> and <strong>those set by bookmakers</strong>.</p><h4>Odds Terminology</h4><p><strong>Odds:</strong> Odds, in a broad sense, represent the ratio of the probabilities of different outcomes. In the domain of sports betting, they serve as a means to convey the likelihood of an event’s occurrence, thereby enabling bettors to gauge the potential return on their bets.</p><p><em>Example:</em> Consider Team A and Team B, who have played 10 matches against each other. Team A wins 8 of these matches, while Team B wins 2. The odds for Team A winning are thus 8/2, indicating a higher probability of victory. Conversely, the odds of Team B winning are 2/8, reflecting a lower chance of success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*LShcfZmNJp8G4URq" /></figure><p><strong>Fractional Odds:</strong> Predominantly used in the UK and Ireland, particularly for horse racing, fractional odds are similar to the general concept of odds but with a twist: the fraction is inverted to indicate the potential return on a wager.</p><p><em>Example:</em> If you bet $10 on Team B, which has odds of 2/8, the corresponding fractional odds would be inverted to 8/2 (or simplified to 4/1). Winning this bet means you would receive $40 in addition to getting your original $10 wager back, effectively earning four times your wager. This illustrates that for every dollar staked, you win four dollars upon a successful bet.</p><p><strong>Decimal Odds:</strong> Decimal odds, frequently referred to as European odds, are a widely adopted format in sports betting across the globe. They quantify the total potential payout as a multiple of the wager, incorporating the original stake in the event of a successful bet.</p><p><em>Example:</em> If Team B’s fractional odds are 8/2, converting these to decimal odds results in a figure of 4.0. To account for the return of the original stake, an additional 1.0 is added, bringing the decimal odds to 5.0. This means that a $10 bet on Team B, if successful, would yield a total return of $50 — comprising the $10 stake and a $40 win.</p><p><strong>Moneyline Odds:</strong> Known as American odds, Moneyline odds are prevalent in the United States. This format specifies how much one needs to bet to win $100 (negative odds) or the potential winnings from a $100 bet (positive odds).</p><p><em>Examples:</em></p><ul><li><em>Positive Moneyline:</em> For Team B with a moneyline of +400, a $100 wager would result in a $400 win. This illustrates that for every dollar bet, four dollars are won, similar to the principle of fractional odds but expressed in a format familiar to the American market.</li><li><em>Negative Moneyline:</em> Conversely, if Team A has a moneyline of -400, it means one must bet $400 to win $100. This setup typically indicates a strong favourite, as a significantly larger amount must be risked for a comparatively small return.</li></ul><p><strong>Probability:</strong> In the domain of sports betting, probability quantifies the chance of a particular outcome happening, expressed as a number between 0 and 1. This numerical value reflects the expected frequency of an outcome within a range of absolute certainty (1) or impossibility (0). The formula to calculate probability from odds is given by Probability=1/DecimalOdds ×100</p><p>Simply put, if Team A wins 80% of their matches (represented as 0.8 in probability terms), it means they are expected to win 8 out of 10 times. Conversely, Team B, with a win rate of 20% (or 0.2 in probability terms), is expected to win 2 out of 10 matches.</p><p><strong>Implied Probability:</strong> Implied probability is a key concept in sports betting, reflecting the probability of an outcome as suggested by the bookmaker’s odds. It is important to note that the implied probability is an estimation based on the odds provided and may not always match the ‘true’ probability of an event occurring. This discrepancy arises because bookmakers adjust odds for various reasons, including balancing their books or reacting to market movements.</p><p>With these foundational definitions in mind, we will focus our further analysis on <strong>decimal odds</strong> and <strong>probabilities</strong> in <strong>football</strong> sports betting. This approach will allow us to dig deeper into the most commonly engaged betting markets, providing a clearer understanding of how odds are set and how bettors can interpret them to make informed decisions.</p><h4><strong>Markets in football sports betting</strong></h4><p>In football betting, the variety of markets available allows punters to wager on numerous aspects of a match. For high-profile games, options can range from predicting the first goal scorer to identifying who will secure the first corner, alongside more unconventional bets. However, our focus will be on the more accessible and widely understood markets that provide an easier entry point for beginners.</p><ul><li><strong>1X2 (Three-Way Win):</strong> This is among the most straightforward and popular betting formats. It simply involves betting on the outcome of a match after 90 minutes: ‘1’ signifies a home win, ‘X’ indicates a draw, and ‘2’ points to an away win. This market is particularly liquid and user-friendly, making it an ideal starting point for those new to football betting.</li><li><strong>DC (Double Chance):</strong> The Double Chance market offers a way to bet on two out of the three possible outcomes of a match with a single wager. Options include betting on a Home win or Draw (1X), an Away win or Draw (X2), or avoiding the draw altogether with a Home win or Away win (12). This approach is more conservative than a straightforward 1X2 bet, essentially serving as a risk-mitigated version of the latter or, put differently, a variation of 1X2 betting with an added safety net.</li><li><strong>OU (Over/Under):</strong> In Over/Under betting, the focus is not on the precise scoreline but rather on the total number of goals scored in the match, with bets placed on whether this total will exceed or fall short of a bookmaker-defined threshold, such as 2.5 goals. This market abstracts from the match’s outcome to concentrate solely on goal totals, offering a distinct betting perspective.</li></ul><p>While we will not look into the complexities of Asian handicaps or the specifics of payouts for lines like Over/Under 1.25, it is important to recognize that the concepts behind these odds mirror those of more intricate markets. Our exploration will prioritize understanding the basic market mechanisms and the fundamentals of bookmaking, providing a solid groundwork for navigating the broader landscape of sports betting.</p><h4><strong>Real-life example</strong> (Germany Bundesliga 1–3 from 2008–2022)</h4><p>In our real-world analysis, we explore data spanning 14 seasons of German football, covering Bundesliga 1, Bundesliga 2, and Bundesliga 3 from 2008 to 2022. This comprehensive dataset, sourced from <a href="http://oddsportal.com/">oddsportal.com</a> and <a href="http://sofascore.com/">sofascore.com</a>, includes odds from multiple bookmakers across various markets, alongside some player data, totalling 13,887 matches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlHai901y8-89ddMbMgO6g.png" /><figcaption>Figure 1: Matches per season analyzed (n=13887)</figcaption></figure><p>Our examination reveals notable patterns in game outcomes: the most common scoreline, occurring in 12.73% of matches, is 1:1. Matches with over 7 goals were rare outliers and excluded from our analysis (n=25). The concept of ‘home advantage’ is clearly supported, with approximately 44% of matches resulting in a home win. Draws accounted for 27% of outcomes, while away wins made up 29%. Interestingly, only 32% of games featured more than 3 goals. A shift is observed in the Bundesliga, where away wins increase to 30.5% and draws decrease to 24.5%, suggesting a more competitive environment and a greater inclination towards securing wins to maintain league standing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfPvIwMmkTZOIVRNtvUb1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5l-mdFnI5bLOlVlw6bxPMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syzppBCXV160jMEOVDZEng.png" /><figcaption>Figure 2: Goal distribution heatmap per league</figcaption></figure><p>This distribution pattern directly influences the odds. Analyzing data from bet365 reveals the following statistical measures for different outcomes:</p><pre>╒═════════════════════╤════════╤══════════╤═══════╤════════╤════════╕<br>│ Outcome             │   mean │   median │   std │   skew │   kurt │<br>╞═════════════════════╪════════╪══════════╪═══════╪════════╪════════╡<br>│ Home Win Odds       │   2.43 │     2.15 │  1.27 │   5.26 │  45.81 │<br>├─────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ Away Win Odds       │   3.87 │     3.30 │  2.41 │   4.63 │  38.50 │<br>├─────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ Draw Odds           │   3.67 │     3.40 │  0.84 │   6.13 │  70.48 │<br>╘═════════════════════╧════════╧══════════╧═══════╧════════╧════════╛</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fP_YMVJdMaMr-bIQXUAFQ.png" /><figcaption>Figure 3: Distribution of Odds for the Bundesliga 1./2./3. between 2008–2022 on bet365</figcaption></figure><p>The most volatile category is the odds for the away win. This can be attributed to the inverse of the ‘home advantage’, leading to significantly higher odds when the home team is favoured. All odds categories display a positive skew, indicating the presence of matches with heavily one-sided odds. The elevated kurtosis, especially for draws, highlights the tail risk or the occurrence of outcomes significantly diverging from the central tendency. While converting odds to a logarithmic scale could offer a uniform perspective on changes, our current focus is on understanding the raw numbers to gain an initial grasp of the odds landscape without altering the scale.</p><p>In addition to the initial analysis, it is essential to examine the trends in betting odds over time. We focus on the opening odds (the initial odds set by the bookmaker) and the closing odds (the final odds offered before the match starts). By applying the same descriptive statistical methods previously discussed, we arrive at the following insights regarding the movement of odds from their opening to closing values:</p><pre>╒════════════════════════════╤════════╤══════════╤═══════╤════════╤════════╕<br>│                            │   mean │   median │   std │   skew │   kurt │<br>╞════════════════════════════╪════════╪══════════╪═══════╪════════╪════════╡<br>│ (&#39;Home Win&#39;, &#39;Closed&#39;)     │   2.43 │     2.15 │  1.27 │   5.26 │  45.81 │<br>├────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;Home Win&#39;, &#39;Open&#39;)       │   2.37 │     2.15 │  1.13 │   5.01 │  39.84 │<br>├────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;Away Win&#39;, &#39;Closed&#39;)     │   3.87 │     3.30 │  2.41 │   4.63 │  38.50 │<br>├────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;Away Win&#39;, &#39;Open&#39;)       │   3.72 │     3.20 │  2.10 │   4.01 │  26.09 │<br>├────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;Draw&#39;, &#39;Closed&#39;)         │   3.67 │     3.40 │  0.84 │   6.13 │  70.48 │<br>├────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;Draw&#39;, &#39;Open&#39;)           │   3.59 │     3.40 │  0.74 │   6.17 │  68.98 │<br>╘════════════════════════════╧════════╧══════════╧═══════╧════════╧════════╛</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slWG3QDTFfw22MnGYJmKyQ.png" /><figcaption>Figure 4.1: Difference in distribution between open &amp; closed odds</figcaption></figure><p>A key observation from our analysis is that, on average, all outcomes exhibit improved odds, albeit with an increase in volatility, as indicated by the standard deviation. This enhancement in odds across the board may be credited to market efficiency, where bookmakers aim to present more attractive odds to reduce their exposure as the match draws closer. This scenario often occurs when liquidity increases, prompting bookmakers to adjust their odds to balance or hedge their risks more effectively. Additionally, the statistical metrics suggest the presence of more outliers in the closing odds compared to the opening odds, highlighting the dynamic nature of the betting landscape as game time approaches.</p><pre>╒══════════════╤══════════════════════════════════╤════════════════════════════════════╤═════════════════════════════════╤══════════════════════════════════╤════════════════════════════════════╤═════════════════════════════════╕<br>│ Outcome      │   (&#39;Open_to_Close_Diff&#39;, &#39;mean&#39;) │   (&#39;Open_to_Close_Diff&#39;, &#39;median&#39;) │   (&#39;Open_to_Close_Diff&#39;, &#39;std&#39;) │   (&#39;Open_to_Close_Perc&#39;, &#39;mean&#39;) │   (&#39;Open_to_Close_Perc&#39;, &#39;median&#39;) │   (&#39;Open_to_Close_Perc&#39;, &#39;std&#39;) │<br>╞══════════════╪══════════════════════════════════╪════════════════════════════════════╪═════════════════════════════════╪══════════════════════════════════╪════════════════════════════════════╪═════════════════════════════════╡<br>│ Home Win     │                             0.06 │                               0.00 │                            0.43 │                             1.96 │                               0.00 │                           12.72 │<br>├──────────────┼──────────────────────────────────┼────────────────────────────────────┼─────────────────────────────────┼──────────────────────────────────┼────────────────────────────────────┼─────────────────────────────────┤<br>│ Away Win     │                             0.15 │                               0.02 │                            0.92 │                             3.63 │                               0.69 │                           18.10 │<br>├──────────────┼──────────────────────────────────┼────────────────────────────────────┼─────────────────────────────────┼──────────────────────────────────┼────────────────────────────────────┼─────────────────────────────────┤<br>│ Draw         │                             0.09 │                               0.05 │                            0.30 │                             2.37 │                               1.35 │                            6.69 │<br>╘══════════════╧══════════════════════════════════╧════════════════════════════════════╧═════════════════════════════════╧══════════════════════════════════╧════════════════════════════════════╧═════════════════════════════════╛</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0-omJ_3xsTXXrgolN1YrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVOeQpvhrqKQE3d4pGjhtw.png" /><figcaption>Figure 4.2: Difference in odds (Closed-Open) absolute &amp; relative</figcaption></figure><p>Upon examining the differences between the opening and closing odds, it becomes evident that, on average, the improvements are notable across all betting outcomes: home wins see an enhancement of 0.06, draws by 0.09, and away wins significantly by 0.15. When these changes are expressed as relative percentages, the average improvements translate to 3.63% for away wins, 2.37% for draws, and 1.96% for home wins. This pattern suggests that placing bets closer to the start of the match generally yields better odds than those available immediately after they are released by bookmakers, at least on average. A deeper look into the median values reveals that draw outcomes experience the most significant median increase, indicating more consistent adjustments for these bets. Visual analysis further supports that for most instances across these outcomes, there is a slight improvement in odds, with the most frequent shift being within the 0–1% range for all three outcomes.</p><p>Turning our attention to another betting market, we explore the Over/Under (OU) market with a 2.5-goal line at bet365 to determine if similar trends are evident. Analyzing the statistical measures for both ‘Over 2.5 goals’ and ‘Under 2.5 goals’ from opening to closing odds reveals the following:</p><pre>╒════════════════════════════════════╤════════╤══════════╤═══════╤════════╤════════╕<br>│                                    │   mean │   median │   std │   skew │   kurt │<br>╞════════════════════════════════════╪════════╪══════════╪═══════╪════════╪════════╡<br>│ (&#39;bet365_OU_2.50_over&#39;, &#39;Closed&#39;)  │   1.87 │     1.85 │  0.25 │   0.07 │   0.18 │<br>├────────────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;bet365_OU_2.50_over&#39;, &#39;Open&#39;)    │   1.86 │     1.85 │  0.21 │  -0.24 │  -0.11 │<br>├────────────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;bet365_OU_2.50_under&#39;, &#39;Closed&#39;) │   2.01 │     1.95 │  0.40 │   2.83 │  14.41 │<br>├────────────────────────────────────┼────────┼──────────┼───────┼────────┼────────┤<br>│ (&#39;bet365_OU_2.50_under&#39;, &#39;Open&#39;)   │   1.99 │     1.95 │  0.33 │   2.66 │  11.85 │<br>╘════════════════════════════════════╧════════╧══════════╧═══════╧════════╧════════╛</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E25l4524pn2dFAUOI0Kzsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2fgf1GIjmpS61HEjfoN2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqGRzhxgTWgouVeb1RnsMg.png" /><figcaption>Figure 5: Difference in odds for OU market</figcaption></figure><h4><strong>Conclusion and Implications</strong></h4><p>In this analysis we investigated betting odds across various markets, focusing on the trends between opening and closing odds for different outcomes. Our findings revealed that, on average, closing odds offer slightly better value across the board, with notable improvements in the odds for away wins in the 1X2 market and both ‘Over’ and ‘Under’ in the OU 2.5 goals market. However, this increase in value is accompanied by greater volatility, as indicated by a rise in standard deviation and more pronounced positive skewness in closing odds. Additionally, the dataset used for this analysis, encompassing 14 seasons of the German Bundesliga, has been made available on <a href="https://www.kaggle.com/datasets/georgpolownikow/football-odds-and-players-german-leagues/data">Kaggle</a> for further exploration. This study underscores the dynamic nature of sports betting markets and highlights opportunities for bettors to potentially capitalize on shifts in odds leading up to a match.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c2123e920c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master MATLAB: Essential Tips and Tricks That Will Boost Your Coding Efficiency Overnight]]></title>
            <link>https://medium.com/@schoepfloeffel/master-matlab-essential-tips-and-tricks-that-will-boost-your-coding-efficiency-overnight-e81786be8b40?source=rss-c52c7ebcf20a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e81786be8b40</guid>
            <category><![CDATA[matlab]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[progamming]]></category>
            <dc:creator><![CDATA[Schoepfloeffel]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 15:26:50 GMT</pubDate>
            <atom:updated>2024-01-10T15:26:50.142Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Unleash the full potential of MATLAB with these little-known, expert-level tips</strong></h4><blockquote>“MATLAB is an F-Tier programming language”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtRDO4UijR0bwS4xzkcSbA.png" /><figcaption><em>DALL-E</em>, version 3, OpenAI, 05Jan. 2024, labs.openai.com/</figcaption></figure><p>A sentiment echoed within most parts of the programming community, primarily due to its ambiguous syntax, complexities in global namespace management, lack of in-depth documentation, and overly intuitive functions that attempt to anticipate user behaviour. This perspective is particularly prominent when comparing MATLAB to other more general-purpose programming languages. After three years of MATLAB coding and comparing it to my experience with more popular languages like C or Python, I share this sentiment. Despite its quirks, MATLAB is still rather popular and holds rank 14 in the <a href="https://www.tiobe.com/tiobe-index">TIOBE index</a> (Nov 2023). I argue that MATLAB is specifically designed for engineers, scientists, quants, and data analysts and less for software engineers. MATLAB is more about interactivity, visuals, and ease of use for the engineering and scientific community.</p><p><strong>What is this article about? </strong>Whether you’re delving into groundbreaking research or innovative industry applications, this article will provide you with valuable insights and advanced techniques in MATLAB programming. I will go into detail about the most common problems I experienced during my MATLAB journey and how to write more readable and maintainable code. For hands-on learners, I’ve included illustrative code examples in a live script on my <a href="https://github.com/Schoepfloeffel/matlab_expert_tips">GitHub</a>.</p><p><strong>Who should read this article? </strong>My primary intended audience consists of engineers without an extensive software background who aim to leverage the MATLAB language in their daily work.</p><p>Please note, that this article focuses exclusively on MATLAB’s application and coding skills in engineering contexts and does not cover broader programming, software design, or architectural principles. We’ll focus on functional programming within MATLAB, touching upon object-oriented concepts only lightly. If you are a seasoned programmer, you will already be familiar with most of the concepts outlined here.</p><p><strong>What are the prerequisites? </strong>A good deal of familiarity with MATLAB and knowledge about basic data types.</p><p><strong>What will you learn and how will it improve your abilities? </strong>This article aims to help you build a solid foundation in writing functions/code and covers the following points:</p><ul><li>Writing more readable and maintainable code</li><li>Understanding data types and assessing the use cases</li><li>Investigating the inner workings of the language to solve daily problems</li><li>Producing expert-level documentation</li></ul><p>Get ready to transform your approach to engineering projects with these advanced MATLAB techniques!</p><h4><strong>TLDR: Time can be more valuable than money. Scroll to the bottom of the article to get the TLDR!</strong></h4><h4><strong>1. Understand Scripts, Functions and Object-Oriented Programming and when to use it</strong></h4><p><strong>Scripts </strong>are a series of MATLAB commands stored in a file. As practical problem-solvers, engineers often favour scripts for their straightforward, pragmatic approach. However, while scripts are great for ”quick and dirty” solutions, relying solely on them, especially in complex projects, can be precarious. The risk of losing track of variables or facing conflicts is high. The code is bound to break at a certain point.</p><p><strong>Functions </strong>contain one or more sequential commands. They can accept inputs and return outputs. I see most engineers begin writing functions after their initial “novice phase”. Functions can be more versatile in the parametrization and the isolated namespace enhances modularity and reusability. It’s common to see engineers’ projects evolve into a collection of functions, orchestrated within a “master script”. However, navigating through someone else’s functions can be challenging. Questions often arise about the appropriate data types for arguments, the sequence of function calls, and potential changes in function outputs. To stress this point, you can take a look at the most prominent project on the <a href="https://www.mathworks.com/matlabcentral/fileexchange/">MATHWORKS file exchange</a>. Because functions are so prominent, the article will focus more on examples of how to write proper functions for your peers.</p><p>While<strong> Object-Oriented Programming</strong> (OOP) is less frequently used in MATLAB compared to functional programming, it becomes immensely valuable when dealing with complex, large-scale applications. OOP allows for sophisticated data abstraction and component-based programming. Think of an object as a custom data structure equipped with its own attributes and methods. This approach can significantly enhance your programming capabilities, especially in structuring large-scale projects. For those interested in delving deeper, I recommend exploring MATLAB’s official <a href="https://www.mathworks.com/company/newsletters/articles/introduction-to-object-oriented-programming-in-matlab.html">resources on OOP</a>, which provide a solid foundation for understanding this powerful programming paradigm and its application in MATLAB.</p><blockquote>Summary: Scripts are ideal for simple tasks and personal use. Functions are more versatile, although they require you to follow certain principles for maximum efficacy. These days OOP is not very prominent within the MATLAB community, but we can make it more popular :). If you are working on a complex project, I encourage you to learn some OOP approaches for MATLAB.</blockquote><blockquote>Depending on the complexity of your project, choose the approach — scripting, functional, or object-oriented — that best enhances your code’s organization, readability, and efficiency.</blockquote><h4><strong>2. Use argument validation to be explicit and break less code</strong></h4><p>The function below is a simple one with no argument validation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c26d93187e4c022070beb9c6d07daff2/href">https://medium.com/media/c26d93187e4c022070beb9c6d07daff2/href</a></iframe><p>In MATLAB, effective argument validation can significantly enhance your function’s robustness. There are three levels to consider:</p><ol><li>Do not use: A lot of if-clauses checking the function inputs. While straightforward, this will clutter your code.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/587e85bb4a352d6bb87c8b856f577cb4/href">https://medium.com/media/587e85bb4a352d6bb87c8b856f577cb4/href</a></iframe><p>2. If necessary, do use: <a href="https://www.mathworks.com/help/matlab/ref/inputparser.html">inputParser</a> built-in class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a5e34d7dba39a8e60ffb61c6787f2b2/href">https://medium.com/media/9a5e34d7dba39a8e60ffb61c6787f2b2/href</a></iframe><p>Available since 2007, you can parse the inputs and use <a href="https://mathworks.com/help/matlab/ref/validateattributes.html">validateattributes</a>. This built-in class allows flexible input parsing and custom validation functions. While being useful, it can make your code less readable.</p><p>3. Do use: Input/Output <a href="https://www.mathworks.com/help/matlab/ref/arguments.html">Argument Blocks</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3b3277d49e7ea031afe7be269d7cb85/href">https://medium.com/media/c3b3277d49e7ea031afe7be269d7cb85/href</a></iframe><p>Introduced in 2019, Input/Output Argument Blocks make it easy to handle data types, impose constraints and set defaults. They are more pleasant to read and more concise in comparison to the inputParser.</p><p>Imagine a function that takes a String input argument as the expression for a switct statement. Your switch statement has three possible cases and also one default case. Using argument validation, we can check the input at the beginning of the function, set a default and give the user precise feedback if there is a problem with the passed input argument — All with only one line of code. From a design perspective, we not only validate arguments but discourage using the <a href="https://mathworks.com/help/matlab/ref/varargin.html">varargin</a> keyword because we define every input parameter explicitly.</p><p>Note: You can do the same thing for the output arguments. See the official documentation on <a href="https://www.mathworks.com/help/matlab/matlab_prog/function-argument-validation-1.html">function argument validation</a>.</p><blockquote>Summary: Use <a href="https://www.mathworks.com/help/matlab/matlab_prog/function-argument-validation-1.html">Input/Output Argument Blocks</a> and be explicit, avoid using <a href="https://mathworks.com/help/matlab/ref/varargin.html">varargin</a>, and use <a href="https://www.mathworks.com/help/matlab/ref/inputparser.html">inputParser</a> primarily for very exotic validation or legacy code where Argument Blocks are limited.</blockquote><h4>3. Use String instead of Chars</h4><p>There is confusion regarding the usage of <a href="https://mathworks.com/help/matlab/ref/char.html">Char</a> and <a href="https://mathworks.com/help/matlab/ref/string.html">String</a> within MATLAB. Let’s first see how you define a variable as a Char Array or a String. I deliberately say Char “Array”<strong>,</strong> since you can think of it as a sequence of individual characters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b42ba362f02416ae8457215b0f286eb/href">https://medium.com/media/0b42ba362f02416ae8457215b0f286eb/href</a></iframe><p>Thus, we can do indexing/slicing operations on Char Arrays like with a numeric Array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35cd47b56010f448ae3d32ec661e2d56/href">https://medium.com/media/35cd47b56010f448ae3d32ec661e2d56/href</a></iframe><p>In comparison, MATLAB treats a String as a single element, even within Arrays. Therefore, we are able to use Strings in Arrays like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ea71b532bc9addb2ab8294095eaf69f/href">https://medium.com/media/5ea71b532bc9addb2ab8294095eaf69f/href</a></iframe><p>Before Strings, Char Arrays were often wrapped in Cell Arrays for similar functionality. Note that the handling of Strings can be a bit different because we cannot use the indexing/slicing operations.</p><p>However, MATLAB already has <a href="https://www.mathworks.com/help/matlab/characters-and-strings.html">built-in functions to manipulate </a><a href="https://www.mathworks.com/help/matlab/characters-and-strings.html">Strings</a> effectively which is easier to read and more versatile than Char Array manipulation.</p><blockquote>Summary: Prefer the data type <a href="https://www.mathworks.com/help/matlab/ref/string.html">String</a> (since 2016) over <a href="https://www.mathworks.com/help/matlab/ref/char.html">Char</a> (Arrays) for their easier manageability and modern capabilities. Use MATLAB’s powerful String functions for efficient text handling. Strings are defined with double quotes “.</blockquote><h4>4. Use sprintf (formatted printing) instead of Char concatenation</h4><p>This tip is closely related to the last section.</p><p>Let’s say we need to generate a String as a name for a file to be saved. Here is a rather verbose code to generate this formatted text using Char concatenation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec73dfc18a5a87a98fe15a1d0d9902c/href">https://medium.com/media/bec73dfc18a5a87a98fe15a1d0d9902c/href</a></iframe><p>Is it that bad? It is working, right!? Well, what happens if we change the input and add an identifier with three fixed digits?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7d2e430b4f796f2d526fa0ab6bc9769/href">https://medium.com/media/a7d2e430b4f796f2d526fa0ab6bc9769/href</a></iframe><p>Switching to <a href="https://mathworks.com/help/matlab/ref/sprintf.html">sprintf</a> for String generation is a game-changer, especially if you’re accustomed to verbose Char concatenation methods, in just one line of code. If you use other programming languages too, you probably know sprintf already.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1e761b8792d6f2fa350e7bbb5837368/href">https://medium.com/media/b1e761b8792d6f2fa350e7bbb5837368/href</a></iframe><p>We would need to worry about the versatility and edge cases that might arise. Sprintf elegantly formats various data types into Strings, handling complexity and variability with ease.</p><blockquote>Summary: Opt for <a href="https://mathworks.com/help/matlab/ref/sprintf.html">sprintf</a> to create Strings. It’s not only more robust and versatile but also significantly enhances the readability of your code, making String manipulations a breeze.</blockquote><h4>5. Start using “iterators”/single row vectors in “for” loops</h4><p>MATLAB does not have a built-in iterator concept (or at least I haven’t found a default iterator semantic without writing my own class for this), however, we can cheat a bit to get a similar behaviour.</p><p>First some iterator background… In many programming languages, iterators are objects used to loop through collections. They enable step-by-step traversal, allowing the <a href="https://mathworks.com/help/matlab/ref/for.html">for</a> keyword to process each element in the collection. Usually, I have seen for loops used as simple counters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/405023ce328969d5169b329ebec11c04/href">https://medium.com/media/405023ce328969d5169b329ebec11c04/href</a></iframe><p>What happens if we want to loop over some specific Struct fields? The simple counter needs to be adjusted for Structs. However, the “iterator” method enhances code clarity and maintainability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d05eb38d3104c5bd12231dffd2796542/href">https://medium.com/media/d05eb38d3104c5bd12231dffd2796542/href</a></iframe><p>Still, it’s important to note that this technique is primarily applicable to flat Arrays. When working with other data types, like Cell Arrays or Structs, the for loop doesn’t operate as seamlessly as it might with a traditional iterator concept.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e47b56ee2eb5f6f4286a5c3adb54be3e/href">https://medium.com/media/e47b56ee2eb5f6f4286a5c3adb54be3e/href</a></iframe><p>One crucial issue you might have noticed is the inability to modify original data directly in the approach we discussed. We are not able to modify our original data with this semantics because we do not have a reference to the original data. This behaviour is called “<a href="https://www.mathworks.com/help/matlab/matlab_prog/avoid-unnecessary-copies-of-data.html">copy-on-write</a>”. MATLAB lacks a mechanism to define a reference to a value/variable and is also not designed to do so! In the next section, you will learn how to make modifications to data without always using for loops.</p><blockquote>Summary: Use a single row vector in conjunction with the <a href="https://www.mathworks.com/help/matlab/ref/for.html">for</a> keyword for efficient traversal through values in flat Arrays. If modification of the original data is needed, see the next chapter which offers an alternative strategy.</blockquote><h4>6. Master arrayfun, structfun and cellfun</h4><p>You might have already seen this concept used in some code or even used it yourself. The syntax might be a bit confusing to begin with and different to common MATLAB code. Despite seeming complex initially, these functions are incredibly useful. Why should you use them? Your code becomes more readable — once getting used to it :). But we will reflect on this in a second.</p><p>First, let me explain what these functions are used for. As the name suggests, they are used on a specific data type (Array, Struct or Cell) and will apply a function (fun) to them. Here are some code examples for each of them providing an overview.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c89b973c7e425fe6d8113a4aafb8aac3/href">https://medium.com/media/c89b973c7e425fe6d8113a4aafb8aac3/href</a></iframe><p>To recap, we can apply a function to all values within a given data type. We can also parametrize the function handles that we supply. My personal favourite, which I often use to modify an Array of Structs, is the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aad7aacfa92938c9863590ca70ad8acd/href">https://medium.com/media/aad7aacfa92938c9863590ca70ad8acd/href</a></iframe><p>Here, we use the arrayfun function because it is an Array of Structs and apply setfield on each scalar Struct. The cool thing is that the function allows for quick slicing operations on the Array of Structs and precisely controls modifications.</p><blockquote>Summary: a<a href="https://mathworks.com/help/matlab/ref/arrayfun.html">rrayfun</a>, <a href="https://mathworks.com/help/matlab/ref/structfun.html">structfun</a> and <a href="https://mathworks.com/help/matlab/ref/cellfun.html">cellfun</a> apply a function to their respective data type. Thus, we can avoid explicit loops and be more concise.</blockquote><h4>7. Embrace newer data types</h4><p>MATLAB’s continuous updates have introduced new data structures that can enhance your day-to-day work. To clarify, when I mention “data structures” here, I’m referring to ways of organizing data, such as Structs or Cells, rather than basic data types like Integers, Floats or Chars. Two recent data structures are especially notable:</p><ul><li><a href="https://mathworks.com/help/matlab/ref/table.html">Table</a>, available since 2013, can be valuable when handling tabular data and doing data analysis.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ccffd8b1f7084a5ae4ed08bc46084b2/href">https://medium.com/media/1ccffd8b1f7084a5ae4ed08bc46084b2/href</a></iframe><p>You will find more built-in functions that are specifically designed to handle tabular data (e.g. <a href="https://mathworks.com/help/matlab/ref/pivot.html">pivot</a> just came out in the year 2023!)</p><ul><li><a href="https://www.mathworks.com/help/matlab/ref/dictionary.html">Dictionary</a> is the latest data structure and can be seen as a successor of <a href="https://mathworks.com/help/matlab/ref/containers.map.html">container.Map</a>. It is a data structure similar to Structs, where you have one or more fields (in Dictionaries called a key) and an assigned value to each of them. The Dictionary can be seen as a list of key-value pairs.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64f21ec094cda8ab81d8c918bf1f93d2/href">https://medium.com/media/64f21ec094cda8ab81d8c918bf1f93d2/href</a></iframe><p>So then what is the difference to Structs? First, the values and also the keys can be any data type. Thus, we are not bound to assign names to our fields using a String/Char Array. Second, the keys are hashed items, resulting in faster lookups. Consequently, if you have many key-value pairs, consider using Dictionaries to improve code execution time.</p><blockquote>Summary: Use <a href="https://mathworks.com/help/matlab/ref/table.html">Tables</a> for tabular data and data analysis. Choose <a href="https://www.mathworks.com/help/matlab/ref/dictionary.html">Dictionaries</a> for dynamic, key-value pair-based data access with fast lookups. Keep using Structs for organized, field-based data storage where clarity and data structure are important.</blockquote><h4>8<em>. Table data structure reigns supreme in data analysis</em></h4><p>In the past years, <a href="https://mathworks.com/help/matlab/ref/table.html">Tables</a> became the best data structure to work with data due to more built-in support. It has gotten easier to aggregate, filter and visualize data. In this section some common functions are showcased with an example table. Let’s start by reading a dataset and applying different concepts.</p><ul><li><strong>Data Aggregation:</strong> Functions like <a href="https://mathworks.com/help/matlab/ref/double.groupsummary.html">groupsummary</a> allow for easy aggregation of data based on groups. You can calculate the mean, median, sum, or custom functions for grouped data.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/478c7fccd884f7f9cbce3a9509e04af1/href">https://medium.com/media/478c7fccd884f7f9cbce3a9509e04af1/href</a></iframe><ul><li><strong>Group Filtering:</strong> Using <a href="https://mathworks.com/help/matlab/ref/double.groupfilter.html">groupfilter</a>, you can filter data based on conditions within groups, making it easier to analyze subsets of your data.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa3a99281c0758b12067dd2d12c33467/href">https://medium.com/media/fa3a99281c0758b12067dd2d12c33467/href</a></iframe><ul><li><strong>Data Manipulation:</strong> Tables support various data manipulations, including sorting, merging, and reshaping data, thus facilitating comprehensive data analysis.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f89cb63aff081652fd4b873b008b14/href">https://medium.com/media/b2f89cb63aff081652fd4b873b008b14/href</a></iframe><ul><li><strong>Combining Data:</strong> You can <a href="https://mathworks.com/help/matlab/ref/table.join.html">join</a> Tables based on common variables, enabling complex data integration tasks.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6f6c677c7f34f14fdefa5fa9aed6984/href">https://medium.com/media/e6f6c677c7f34f14fdefa5fa9aed6984/href</a></iframe><ul><li><strong>Visualization:</strong> Tables integrate well with MATLAB’s plotting functions, allowing for easy visualization of data for analysis and presentation purposes.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0810e619e537026b8616d652f948c3a/href">https://medium.com/media/c0810e619e537026b8616d652f948c3a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*iPl4xYfvagd5HG_BzF18iQ.png" /></figure><blockquote>Summary: <a href="https://mathworks.com/help/matlab/ref/table.html">Tables</a> as data structures are an essential tool for data analysis because they offer versatility and built-in support for aggregations, filtering and visualization.</blockquote><h4>9. Navigate the Nuances of Floating-Point Arithmetic</h4><p>Floating-point arithmetic can lead to subtle errors in computations — a phenomenon intrinsic to how computers represent real numbers. Let’s take a look at the following classic example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69cea30e19f8b932dc3cd188378277b8/href">https://medium.com/media/69cea30e19f8b932dc3cd188378277b8/href</a></iframe><p>Such errors can impact badly designed conditions or can add up to significant errors in scientific computing where high precision is required. It is crucial to understand this concept, to not only write better code but also build precise systems if needed. So how can we tackle this problem?</p><p>First, we need to understand the machine epsilon (<a href="https://mathworks.com/help/matlab/ref/eps.html">eps</a>). This value represents the smallest difference between distinct floating-point numbers in MATLAB’s commonly used double-precision format (here is a <a href="https://www.mathworks.com/matlabcentral/answers/314384-question-about-machine-epsilon">good explanation</a> with hex representation regarding eps and workings under the hood). Depending on your requirements, I recommend the following solutions in MATLAB.</p><ul><li><strong>For conditional checks: </strong>Use <a href="https://mathworks.com/help/matlab/ref/ismembertol.html">ismembertol</a><em> </em>with tolerance value eps<em>. </em>This method helps make accurate comparisons by accounting for floating-point discrepancies.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0f0411ef42f9064da204922402e1c90/href">https://medium.com/media/f0f0411ef42f9064da204922402e1c90/href</a></iframe><ul><li><strong>For high-precision scientific computing</strong>: Check out <a href="https://www.mathworks.com/help/symbolic/vpa.html">vpa</a> (variable-precision arithmetic) or <a href="https://mathworks.com/help/symbolic/digits.html">digits</a> for calculations requiring high precision. This approach allows for more precise results, especially necessary in scientific computations.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca602a4a725ff294e4555fbfc16370b4/href">https://medium.com/media/ca602a4a725ff294e4555fbfc16370b4/href</a></iframe><ul><li><strong>For reduction in significant accumulation of round-off errors with doubles</strong>: Use <a href="https://mathworks.com/help/matlab/ref/round.html">round</a> with a specific decimal precision to make sure to round to the expected number.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dde7ee852bf7e305f55e574753544e16/href">https://medium.com/media/dde7ee852bf7e305f55e574753544e16/href</a></iframe><blockquote>Summary: For conditional checks involving calculated values, <a href="https://mathworks.com/help/matlab/ref/ismembertol.html">ismembertol</a> or a similar tolerance-based approach is recommended to ensure accuracy within the specified conditions. When higher precision is necessary for your calculations, consider using <a href="https://www.mathworks.com/help/symbolic/vpa.html">vpa</a>. However, be aware that while <a href="https://www.mathworks.com/help/symbolic/vpa.html">vpa</a> increases precision, it also significantly lengthens computation time. To reduce the accumulation of errors and keep a low computation time, <a href="https://mathworks.com/help/matlab/ref/round.html">round</a> might be an option.</blockquote><h4>10. Handling missing data with “missing“</h4><p>In MATLAB, we usually represent a missing number with <a href="https://mathworks.com/help/matlab/ref/nan.html">NaN</a> (Not a Number).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/112f285fa0e6b3c5464713f884b35d54/href">https://medium.com/media/112f285fa0e6b3c5464713f884b35d54/href</a></iframe><p>While NaN is used for checks, challenges arise when dealing with non-numeric data types like Strings. To address this, the <a href="https://www.mathworks.com/help/matlab/ref/missing.html">missing</a> type was introduced in 2017, extending the concept of NaN to other data types. The good news is, NaN stays NaN for numeric Arrays, so legacy code keeps working with the missing type. This extension is especially useful for data analysis and aggregations where we work with different data types. To efficiently handle missing values in such cases, use the <a href="https://mathworks.com/help/matlab/ref/mean.html#mw_44035159-4a67-4049-b7c3-b6903c5de7a7">missingflag parameter in aggregation functions</a>.</p><p><strong>Here are some behaviours of missing to keep in mind:</strong></p><ul><li>Numeric Arrays (Double, Single, Duration, calendarDuration) convert missing values to NaN.</li><li>Datetime Arrays translate missing to NaT (Not a Time).</li><li>Categorical Arrays treat missing as &lt;undefined&gt;.</li><li>In String Arrays, missing becomes &lt;missing&gt;.</li><li>Missing values are treated as distinct; e.g. <a href="https://www.mathworks.com/help/matlab/ref/double.unique.html">unique</a> will list each missing value.</li><li>Aggregations on arrays with missing values default to returning missing, use the missingflag parameter (e.g. omitnan or omitmissing) in aggregation functions to ignore missings.</li><li>From 2022 onwards, conditional checks like <a href="https://mathworks.com/help/matlab/ref/ismissing.html">ismissing</a> and <a href="https://mathworks.com/help/matlab/ref/anymissing.html">anymissing</a> are available, extending the functionality of <a href="https://mathworks.com/help/matlab/ref/isnan.html">isnan</a> to other data types.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42a2cc214f4cbd5129e55a39c5f5ff04/href">https://medium.com/media/42a2cc214f4cbd5129e55a39c5f5ff04/href</a></iframe><blockquote>Summary: The <a href="https://www.mathworks.com/help/matlab/ref/missing.html">missing</a> type is the “better” <a href="https://www.mathworks.com/help/matlab/ref/nan.html">NaN</a>. It can handle the missing values of more data types in contrast to the legacy NaN. Missings are treated the same way in common numeric Arrays like NaN for backward compatibility (missing converts to NaN in this use case). Keep the behaviours of missing in mind!</blockquote><h4>11. <strong>Staying updated with MATLAB Release Notes</strong></h4><p>As you have seen in the past sections, we have gotten wonderful improvements in the form of more data types and tools to work with throughout the past few years. Each release brings new features and enhancements. Typically, two MATLAB versions are released each year, named after the year and a suffix with<em> a </em>or <em>b. </em>You can find the release notes <a href="https://www.mathworks.com/help/matlab/release-notes.html">here</a>. They are clustered in subcategories. Check out the sections you are most interested in! Recent MATLAB releases have been a game-changer for me personally. The deployment of applications has gotten easier (more docker support) and advancements in data analysis functionalities have saved a lot of time.</p><blockquote>Summary: Check out the <a href="https://www.mathworks.com/help/matlab/release-notes.html">release notes of new MATLAB releases</a>. Most new functionalities make coding some advanced concepts way easier.</blockquote><h4>12. Effective Debugging with Conditional Breakpoints in MATLAB</h4><p>Even with robust code design, encountering bugs is inevitable. MATLAB’s interpreted nature allows for immediate feedback through running specific lines. Thus, the whole program does not need to be compiled first, and I have often seen the use of immediate feedback by just running specific lines of code or the good old and reliable print statements. However, for more precise troubleshooting, I recommend utilizing MATLAB’s debugger.</p><p>The debugger allows you to examine the state of the program at the breakpoint. The big advantage is, that you can inspect every workspace variable present when the breakpoint is reached. Moreover, we can simply re-run sections and interactively explore the variables in the workspace within our debugger.</p><p>Nevertheless, in more complex applications your breakpoint might be stopping too early and your program is not in the desired state. To only trigger the breakpoint in a specific state (condition), you can right-click on the <a href="https://de.mathworks.com/help/matlab/matlab_prog/set-breakpoints.html">breakpoint and set a condition</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13566e2c22c689167d28d1b7c797b8ec/href">https://medium.com/media/13566e2c22c689167d28d1b7c797b8ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*8ltrDF8cUyrDwu7i9sXVSw.png" /><figcaption>MATLAB window to put in condition for a breakpoint</figcaption></figure><p>Alternatively, you can use <a href="https://www.mathworks.com/help/matlab/ref/dbstop.html">dbstop</a> in the command window.</p><p>Note: To automatically enter debugger mode when an error occurs, use the “Pause at error” option in MATLAB’s menu. This directs you to the exact line where the error is thrown, facilitating immediate debugging. However, be cautious, as the error might not always manifest as expected due to varying implementation details. To further enhance your error handling skills, familiarize yourself with functions like <a href="https://mathworks.com/help/matlab/ref/mexception.html">Mexception</a>, <a href="https://mathworks.com/help/matlab/ref/mexception.throwascaller.html">throwAsCaller</a>, <a href="https://mathworks.com/help/matlab/ref/mexception.rethrow.html">rethrow</a>, and <a href="https://mathworks.com/help/matlab/ref/mexception.throw.html">throw</a>, which offer nuanced ways to manage errors.</p><blockquote>Summary: Choose the debugging approach that best suits your needs, be it through using the debugger, setting conditional breakpoints, or utilizing the “Pause at error” feature.</blockquote><h4>13. Start documenting like a pro (not the help function)</h4><p>At last, you want to document your function so other users and your future self will understand the code. Good documentation starts with clean code and argument validation. Especially Argument Validation Blocks (<a href="#6400">see Section 2</a>) explain input and output parameters in a clear fashion.</p><p>MATLAB’s ecosystem offers various ways to <a href="https://www.mathworks.com/help/matlab/matlab_env/help-resources.html">seek help and document code</a>.</p><p>The most commonly used function <a href="https://mathworks.com/help/matlab/ref/help.html">help</a> displays comments written directly after a function, serving as its documentation. However, there is no clear syntax on how to write the documentation (or at least I could not find any). Additionally, MATLAB’s <a href="https://mathworks.com/help/matlab/ref/publish.html">publish</a> function — particularly useful for .mlx live scripts — allows you to generate HTML outputs, sharing both your code and its output with others.</p><p>During my journey to write MATLAB code documentation, I was still not happy with these tools. I wanted to do something like this type of <a href="https://bwanamarko.alwaysdata.net/matlabdomain/">interactive documentation</a>.</p><p>I dived deeper and found the solution in the <a href="https://github.com/sphinx-contrib/matlabdomain">Sphinx MATLAB extension</a>. Thanks to all the contributors — you eased my work by a lot :).</p><p>To start using the extension, we require Python and install the package. Follow the instructions on their <a href="https://github.com/sphinx-contrib/matlabdomain">GitHub page</a> for installation and usage.</p><p>The extension can parse your code comments and generate a fully functional HTML documentation page for you. Be mindful that it doesn’t autogenerate docstrings, so precision in formatting — including tabs, spaces, and punctuation — is crucial for optimal <a href="https://github.com/Schoepfloeffel/matlab_expert_tips/tree/main/Section13/docs">results</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb7e9b7d09abd9886a4f6bdd160f13c5/href">https://medium.com/media/eb7e9b7d09abd9886a4f6bdd160f13c5/href</a></iframe><p>Note that creating complete HTML documentation using the Sphinx MATLAB extension also involves writing RST files. While it is generally effective, be prepared for occasional parsing bugs due to unhandled edge cases. In my experience, you can work around it but I keep wondering whether I should start contributing and fixing these bugs ;)?</p><p>In one of my projects, I automated the documentation generation and integrated it with CI/CD pipelines for deployment to GitLab Pages. This process has not only streamlined our workflow but also raised awareness among my colleagues about the benefits of efficient documentation, testing and deployment practices. But this is a whole different story :).</p><blockquote>Summary: Leverage the <a href="https://github.com/sphinx-contrib/matlabdomain">Python Sphinx MATLAB extension</a> to get a <a href="https://github.com/Schoepfloeffel/matlab_expert_tips/tree/main/Section13/docs">functional HTML documentation page</a> for your MATLAB application. You can easily host it on services like GitHub or GitLab. You’ll need to write the correct documentation syntax and RST files, but the effort pays off, especially for larger and more complex applications.</blockquote><h4>TLDR</h4><ul><li>[<a href="#e69d">01</a>] | Maintainability &amp; Readability | <em>Understand Scripts, Functions, Classes</em> |</li><li>[<a href="#6400">02</a>] | Maintainability &amp; Readability | <em>Use Argument Validation</em> |</li><li>[<a href="#f9e6">03</a>] | Text Handling | <em>Strings Are Better Than Char Arrays</em> |</li><li>[<a href="#6921">04</a>] | Text Handling |<em> Sprintf For Formatting Text </em>|</li><li>[<a href="#ee86">05</a>] | Looping | <em>Use ‘iterators’ Instead Of Simple Counters</em> |</li><li>[<a href="#087e">06</a>] | Looping | <em>Apply Functions To Each Element (arrayfun, cellfun, structfun)</em> |</li><li>[<a href="#2c10">07</a>] | Datatypes | <em>Use Tables And Dictionaries If Needed</em> |</li><li>[<a href="#96e9">08</a>] | Data Analysis | <em>Tables For Data Analysis </em>|</li><li>[<a href="#9277">09</a>] | Calculation Errors | <em>Handling Precision Correctly Depending On Use Case</em> |</li><li>[<a href="#7011">10</a>] | Missing | <em>Use Missings over NaN</em> |</li><li>[<a href="#37a9">11</a>] | Education | <em>Stay Up To Date </em>|</li><li>[<a href="#90cd">12</a>] | Debugging | <em>Conditional Breakpoints</em> |</li><li>[<a href="#1979">13</a>] | Documentation | <em>Produce A HTML Documentation In Python</em> |</li></ul><blockquote>I hope you find these MATLAB tips useful in your upcoming projects. I’m keen to hear how they work for you, so feel free to share your feedback and experiences!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e81786be8b40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>