<?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 Siddharth Rama Sushil on Medium]]></title>
        <description><![CDATA[Stories by Siddharth Rama Sushil on Medium]]></description>
        <link>https://medium.com/@siddharthramasushil?source=rss-fbf100db3739------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GGZ_m0A6Sv0uO45B</url>
            <title>Stories by Siddharth Rama Sushil on Medium</title>
            <link>https://medium.com/@siddharthramasushil?source=rss-fbf100db3739------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:20:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siddharthramasushil/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[Understanding Tensors in Isaac Lab: Why the Shapes Look Strange and Why Loops Are Slow]]></title>
            <link>https://medium.com/@siddharthramasushil/understanding-tensors-in-isaac-lab-why-the-shapes-look-strange-and-why-loops-are-slow-4255797eac9d?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/4255797eac9d</guid>
            <category><![CDATA[isaac-lab]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[isaac-sim]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[tensor]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 01:16:59 GMT</pubDate>
            <atom:updated>2026-10-26T01:16:59.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>num_envs, unsqueeze and broadcasting, explained for people who think in one robot at a time</h4><p>If you are new to Isaac Lab, you have probably seen shapes like (num_envs, num_samples, 3) and lines like this one:</p><pre>obj_pos_w = obj.data.root_pos_w.unsqueeze(1)</pre><p>It looks over-engineered if you think in terms of one robot in one simulation. When I started writing reward terms for a dexterous grasping environment, it confused me too. Once you see why Isaac Lab arranges its data this way, every shape starts to read like a sentence.</p><h3>Isaac Lab simulates many environments at once</h3><p>This is the one idea everything else follows from. Isaac Lab does not simulate one robot. It simulates hundreds or thousands of copies of your environment in parallel on the GPU, and it stores their state in one big tensor per quantity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fFgRbVYUnM_kFULC.jpg" /><figcaption>Many robots, one simulation: Isaac Lab steps every environment together and stores each quantity in a single tensor. Image: Isaac Lab documentation, BSD-3-Clause.</figcaption></figure><p>So instead of “one robot, one state”, Isaac Lab works with “many robots, one tensor”. That one design decision explains almost every shape you will meet.</p><h3>The golden rule: the first dimension is num_envs</h3><p>Nearly every tensor follows the pattern (num_envs, ..., feature_dim). The environment dimension is there even when you debug with a single environment, because the code is written to scale.</p><p>Take an object’s position in the world frame:</p><pre>obj.data.root_pos_w     # (num_envs, 3)   x, y, z per environment<br>obj.data.root_quat_w    # (num_envs, 4)   orientation per environment<br>obj.data.root_pose_w    # (num_envs, 7)   position + quaternion</pre><p>Each row is one environment. One gotcha worth knowing: the quaternion order changed between Isaac Lab versions (older releases use <em>w, x, y, z</em>, newer ones <em>x, y, z, w</em>), so check the docs for the version you run before you index into it.</p><h3>When each environment has many things</h3><p>Now say you sample points on the surface of the object, maybe to reward fingertips for getting close to it. Each environment has its own set of points:</p><pre>sampled_points_w   # (num_envs, num_samples, 3)</pre><p>Read it left to right: for every environment, num_samples points, each with x, y, z. You want every point relative to its object&#39;s position. The object position has one row per environment, and the points have many rows per environment. That mismatch is on purpose, and broadcasting resolves it.</p><h3>Why not just write a loop?</h3><p>The first version I would have written looks like this:</p><pre>for e in range(num_envs):<br>    for s in range(num_samples):<br>        rel[e, s] = points[e, s] - obj_pos[e]</pre><p>Every iteration is a separate Python operation, and the GPU sits idle between them. I timed the same subtraction with plain NumPy on a laptop CPU, 4,096 environments with 256 points each:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JSKWy6WTywXL44SL.png" /><figcaption>The same subtraction, written as two Python loops and as one broadcast. Measured with NumPy on a laptop CPU; on the GPU the gap only grows.</figcaption></figure><p>About 150 times faster, and on the GPU the gap gets bigger. With thousands of environments stepping every few milliseconds, the loop version is not slow, it is unusable.</p><h3>Broadcasting: one operation, many values</h3><p>Broadcasting lets PyTorch combine tensors of different shapes without copying data. The rule: compare shapes from the right, and any dimension of size 1 stretches to match the other tensor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJWbuaG0kUyZfJLj.png" /><figcaption>obj_pos_w gets a size-1 sample dimension, and broadcasting stretches it across every sampled point in the same environment.</figcaption></figure><p>So the whole loop becomes one line:</p><pre>obj_pos_w = obj.data.root_pos_w.unsqueeze(1)    # (num_envs, 1, 3)<br>relative_points = sampled_points_w - obj_pos_w  # (num_envs, num_samples, 3)</pre><h3>What unsqueeze actually does</h3><p>unsqueeze(1) inserts a dimension of size 1 at position 1. (num_envs, 3) becomes (num_envs, 1, 3). No data moves or changes, only the shape label, and that size-1 slot is what tells broadcasting where to stretch. Without it, PyTorch would line up (num_envs, 3) against the last two dimensions of the points, (num_samples, 3), and either throw an error or quietly pair the wrong things.</p><p>squeeze(dim) does the reverse and drops a size-1 dimension, for example after you reduce over the samples:</p><pre>dist = relative_points.norm(dim=-1)          # (num_envs, num_samples)<br>closest = dist.min(dim=1, keepdim=True)[0]   # (num_envs, 1)<br>reward = -closest.squeeze(1)                 # (num_envs,)  one reward per env</pre><h3>Reading any Isaac Lab shape</h3><p>A mental model that helped me: read each dimension as an answer to “how many of this thing exist per environment?”</p><ul><li>(num_envs,): one number per environment, like a reward or a done flag.</li><li>(num_envs, 3): one vector per environment, like a root position.</li><li>(num_envs, num_joints): one value per joint per environment.</li><li>(num_envs, N, 3): N points per environment, like sampled surface points or a point cloud.</li></ul><p>Isaac Lab tensors are not complicated. They are explicit. Once you read the first dimension as “for every environment”, the rest of the shape tells you exactly what you are holding, and the code stops looking like puzzles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4255797eac9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Jordan Form: Get System Insights from Messy State Matrices]]></title>
            <link>https://medium.com/@siddharthramasushil/understanding-jordan-form-get-system-insights-from-messy-state-matrices-63174a1f5581?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/63174a1f5581</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[control-system]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 06:37:20 GMT</pubDate>
            <atom:updated>2025-11-22T06:39:31.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-9d3unFcU3JnDlddD-qtA.png" /></figure><h3>Why Linear Systems Give Us Messy Matrices</h3><p>When we model real-world dynamical systems — whether it’s a robot arm, an aircraft, a chemical reactor, or an electrical circuit — we naturally arrive at a set of differential equations that describe how the system evolves over time. We define <strong>state variables</strong> x1,x2,…,xn that capture everything we need to know about the system at any moment: positions, velocities, temperatures, pressures, voltages, currents, and so on.​</p><p>For linear time-invariant (LTI) systems, these relationships take the ​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*rknmxTRVslPTP5dbz1pYbw.png" /></figure><p>where x˙ represents the rates of change of our states, A is the <strong>state matrix</strong> that describes how states influence each other, B is the input matrix, and u is the control input. The matrix A emerges naturally from the physics, chemistry, or engineering principles governing the system.​</p><p>But here’s the problem: this matrix A is usually a <strong>mess</strong>. The entries are filled with seemingly arbitrary numbers that mix together the influences of different states on one another. Looking at A directly tells you almost nothing about how the system actually behaves. Will it be stable? Will it oscillate? What are the dominant time scales? These critical questions remain hidden in the tangled web of coupling coefficients.​</p><h3>The Fundamental Challenge: Decoupling or Understanding Coupling</h3><p>The core problem is this: in the original coordinate system (the states we chose based on physical considerations), the system dynamics are <strong>coupled</strong> — each state’s evolution depends on multiple other states in complicated ways. Mathematically, when you try to solve the differential equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*BxU7TyrUfU5fKHPd82sn4Q.png" /></figure><p>you get a system of coupled equations that are difficult to solve analytically and even harder to interpret.​</p><p>What we desperately need is a <strong>coordinate transformation</strong> — a clever change of variables that either:</p><ol><li><strong>Completely decouples</strong> the system, so each new state variable evolves independently, or</li><li><strong>Minimally couples</strong> the system in the simplest possible structure, making the coupling transparent and understandable.​</li></ol><p>This is where the search for the “right” basis begins. We’re looking for a coordinate system in the state space where the matrix A becomes as simple as possible — ideally diagonal, but if not, then as close to diagonal as we can get.​</p><h3>A 2D Example: The Shear Transformation</h3><p>Let’s ground this abstract discussion with a concrete example. Consider a 2D system where our state space is R² (planar) and we’ll decompose it into two natural subspaces:​</p><ul><li>M<em>1</em>: the x-axis, where vectors look like (x,0)</li><li>M<em>2</em>: the y-axis, where vectors look like (0,y)</li></ul><p>These subspaces are orthogonal and together span the entire space. Now suppose our system matrix is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*Mpzzo2nQTZtiNpBrudN8Aw.png" /></figure><p>This is a <strong>shear transformation</strong>. Let’s see what it does:​</p><ul><li>When we apply A to a vector on the x-axis:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*xlfQEVIEfeJyYE8R_zhEqg.png" /></figure><p>The vector stays on the x-axis — no coupling!​</p><ul><li>When we apply A to a vector on the y-axis:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*Wsdaho2BUVbFFQ2zC7udJg.png" /></figure><p>The vector now has components in both x and y directions — coupling!​</p><p>Looking at the block structure of A:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*2wXo43ao7Dp80DS87W9kUw.png" /></figure><p>The block A<em>11</em>=1 tells us how the x-axis transforms within itself (just scaling by 1). The block A<em>22 </em>= 1 tells us how the y-axis transforms within itself (also scaling by 1). But the off-diagonal block A<em>12 = </em>1<em> </em>reveals the <strong>coupling</strong>: the y-axis influences the x-axis.​</p><p>This simple 2D example shows us something profound: <strong>the structure of the matrix reveals which subspaces are independent and which are coupled</strong>. The x-axis is an <strong>invariant subspace</strong> (it maps to itself), but the y-axis is not — vectors in M2 get pushed into M1.​</p><h3>The Big Question: How Do We Find the “Right” x and y Axes?</h3><p>In our 2D shear example, we could visually identify the x and y axes as natural coordinate directions. But what if we’re working in 10-dimensional space? Or 100-dimensional space? How do we systematically find the coordinate system where the coupling structure becomes transparent?​</p><p>This is where <strong>eigenvalues and eigenvectors</strong> enter the picture.</p><h3>Eigenvalues and Eigenvectors: The A-Invariant Subspaces</h3><p>An <strong>eigenvector</strong> v of matrix A is a special direction in state space with a remarkable property.​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*25ZrmBIIHYYCprGzijzsrQ.png" /></figure><p>When A acts on v, it doesn’t change the direction — it only scales the vector by the factor λ (the <strong>eigenvalue</strong>). Geometrically, the line spanned by v is an <strong>A-invariant subspace</strong>: if you start on this line, A keeps you on this line.​</p><p>This is exactly what we’re searching for! If we can find a complete set of eigenvectors that span the entire state space, we can use them as our new coordinate axes. In this <strong>eigenbasis</strong>, the matrix A becomes diagonal.​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*pV1Llk4UYrO_V3Iz_WDsiQ.png" /></figure><p>where P has eigenvectors as columns and D is diagonal with eigenvalues on the diagonal. In this magical coordinate system, the system is <strong>completely decoupled</strong> — each state evolves independently according to its eigenvalue.​</p><p>The physical interpretation is beautiful:</p><ul><li><strong>Eigenvalue</strong> λ: the natural frequency or growth/decay rate of that mode.​</li><li><strong>Real eigenvalue</strong> λ&lt;0: exponential decay (stable mode)</li><li><strong>Real eigenvalue</strong> λ&gt;0: exponential growth (unstable mode)</li><li><strong>Complex eigenvalues</strong> λ=α±iω: oscillatory modes with frequency ω and decay/growth rate α​.</li></ul><h3>The Ideal Case: Perfect Diagonalization</h3><p>When we can find n linearly independent eigenvectors for an n×n matrix, we achieve <strong>complete diagonalization</strong>. The system solution becomes trivial.​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*mey12jJMqFF3ls6piiAFvA.png" /></figure><p>Since D is diagonal, e^Dt is simply:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*HiWqEcOoFaTsw3YpU-DJtg.png" /></figure><p>Each mode evolves independently as a pure exponential or sinusoid. Engineers love this case because the system behavior is completely transparent: look at the eigenvalues, and you immediately know stability, oscillation frequencies, and time scales.​</p><h3>The Harsh Reality: Not All Systems Diagonalize</h3><p>Unfortunately, not all matrices have enough eigenvectors to diagonalize. This happens when the <strong>geometric multiplicity</strong> (the dimension of the eigenspace — how many independent eigenvectors you can find) is less than the <strong>algebraic multiplicity</strong> (how many times that eigenvalue appears as a root of the characteristic equation).​</p><p>Such matrices are called <strong>defective</strong>, and they represent systems where modes are fundamentally <strong>intertwined</strong> — you cannot separate them completely. This is not a mathematical technicality; it reflects real physical coupling in the system that cannot be eliminated by any coordinate change.​</p><p>Our shear matrix example is actually defective! It has eigenvalue λ=1 with algebraic multiplicity 2, but only one independent eigenvector .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/36/1*tsds_H1U3dWQVzmOphxrZw.png" /></figure><p>Try as we might, we cannot find two independent directions that are both invariant under this shear — the shear fundamentally couples the directions.​</p><p>So what do we do? We can’t diagonalize, but we can find the <strong>next best thing</strong>: the <strong>Jordan normal form</strong>.</p><h3>The Systematic Approach: Jordan Form Decomposition</h3><p>Jordan form is the standardized procedure for transforming any matrix into the simplest possible structure when diagonalization fails. It’s a block-diagonal matrix where each block captures one coupled mode family in the cleanest way possible.​</p><p>Here’s the systematic step-by-step process:</p><h3>Step 1: Find All Eigenvalues</h3><p>Solve the characteristic equation.​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*Nw82Yy9EaR4Gvx-J5c_Nlw.png" /></figure><p>This gives you all eigenvalues λ1, λ2, … , λk(possibly with repetitions). These are the <strong>natural frequencies</strong> of your system — the fundamental time scales at which things happen.​</p><p><strong>Engineering insight</strong>: The eigenvalues immediately tell you about stability (negative real parts = stable) and oscillations (imaginary parts = oscillatory).​</p><h3>Step 2: Check Algebraic vs. Geometric Multiplicity</h3><p>For each distinct eigenvalue λ.​</p><ul><li><strong>Algebraic multiplicity m_<em>a</em></strong>: how many times λi appears as a root of the characteristic equation.</li><li><strong>Geometric multiplicity m_<em>g</em></strong>: dimension of null(A−λi) — the number of independent eigenvectors.</li></ul><p>Now I’m sure you’re confused, what does it even MEAN?! Let me elaborate:</p><p>The number of times a specific eigenvalue λi appears as a root of the characteristic polynomial is its algebraic multiplicity. This count tells you <em>how many modes</em> (or fundamental system frequencies/decay rates) mathematically exist, even if they turn out to be repeated or “stacked” atop each other.</p><p>In physical terms for a dynamical system, it’s like counting how many separate springs or oscillators (each with their own natural frequency) should be present, at least in theory)</p><p>The number of independent eigenvectors (geometric multiplicity) tells you how many independent “directions” in state-space can stretch or shrink just by that eigenvalue’s factor — these are the axes you can use to decouple behavior.</p><ul><li>If you have as many eigenvectors as eigenvalues, every direction is independent and your system is easy to analyze.</li><li>If you have fewer, then certain motions are fundamentally linked; pushing one state always moves another, revealing intrinsic coupling (like in a robot with physically coupled joints).</li></ul><p>So you need to compare the <strong>Algebraic multiplicity and Geometric multiplicity</strong> :</p><ul><li>If m_g=m_a for all eigenvalues: congratulations, your matrix is diagonalizable!</li><li>If m_g&lt;m_a for any eigenvalue: you have defectiveness and need Jordan chains.​</li></ul><p><strong>Engineering insight</strong>: Defectiveness means you have <strong>modal coupling</strong> — some system modes cannot be separated and will exhibit polynomial-time behavior in addition to exponential behavior.​</p><h3>Step 3: Build Jordan Chains (For Defective Eigenvalues)</h3><p>For each defective eigenvalue λ, we need <strong>generalized eigenvectors</strong> to form Jordan chains:​</p><p><strong>Find eigenvectors</strong>: Solve the following equation to get ordinary eigenvectors v1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*9RyF0gnTdCyw4sEM_ydb9g.png" /></figure><p><strong>Build the chain</strong>: For each eigenvector v1, try to extend it by solving:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*U-nT9NS-qu4dDNai6C4rxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*YC5v-FlPudQk31lNxVQkcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*oKvq9l7TpsNYlVZ1SRBxCQ.png" /></figure><p><strong>Chain length = Jordan block size</strong>: The length of each chain determines the size of the corresponding Jordan block.​</p><p><strong>Engineering insight</strong>: Each Jordan chain represents a <strong>coupled mode family</strong>. The eigenvector is the “pure” mode, and the generalized eigenvectors capture how this mode influences adjacent coordinates due to the coupling.​</p><h3>Step 4: Construct the Transformation Matrix P and Jordan Form J</h3><p>Arrange all eigenvectors and generalized eigenvectors as columns of matrix P, organized by Jordan chains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*7Fo_f5GT3NOb7vbMwFgiSw.png" /><figcaption>the jordan form</figcaption></figure><p>The similarity transform matrix <em>P</em> for Jordan form is constructed from all the Jordan chains (both genuine eigenvectors and generalized eigenvectors), so that <em>A</em>=<em>P*J*P^-1</em> truly captures both independent and coupled modes of the system. This is what reveals the full modal structure of defective matrices, making the Jordan form so powerful for both theory and applications.</p><p>The Jordan form has a block-diagonal structure:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*3s3AEy0jyaOkCDmNbpeWXQ.png" /></figure><p>Each Jordan block has the form:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*Tq_1HD1i_r690wAfZ3EI1g.png" /></figure><p>A k×k Jordan block represents a coupled subsystem with:</p><ul><li>Eigenvalue λ on the diagonal (the natural frequency)​</li><li>1’s on the super-diagonal (representing minimal coupling between consecutive generalized eigenvectors)​</li><li>Everything else is zero</li></ul><p><strong>Engineering insight</strong>: The Jordan form explicitly shows you the modal structure: which modes are independent (1×1 blocks) and which are coupled (larger blocks).​</p><h3>Step 5: Compute the Matrix Exponential e^{At}</h3><p>The time evolution of the system is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*A-_j76kao-cmawoy1ViT1Q.png" /></figure><p>Using the Jordan form:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*4wVSFz_xp0I785rKG8HYuQ.png" /></figure><p>The beauty of Jordan form is that e^{Jt} is block-diagonal, and each block has a simple pattern:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*mHylLs3yb2DjPMNi58FIwQ.png" /></figure><p>Notice the <strong>polynomial terms in time</strong> (t, t², etc.) multiplying the exponential! These come from the Jordan chain structure and represent the coupling between modes.​</p><p><strong>Engineering insight</strong>: Polynomial-modulated exponentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/63/1*DWe2Mw4W1AffVRAaE9RVRg.png" /></figure><p>are the signature of defective systems. They cause transient behavior different from pure exponentials — initial growth followed by eventual decay if:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*LYpmDZYJSAqRKkgaxSl12A.png" /><figcaption>real part of eigen value is less than 0</figcaption></figure><h3>Step 6: Multiply with Initial Conditions</h3><p>The complete solution is:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*0y7jvE3zM9W_YPOHsIxjew.png" /></figure><p>​</p><h3>Step 7: Analyze System Behavior</h3><p>Now you can read system characteristics directly from the Jordan form:​</p><ul><li><strong>1×1 Jordan blocks</strong> (diagonalizable eigenvalues): pure exponential/oscillatory modes e^{ λt}.​</li><li><strong>Larger Jordan blocks</strong> (defective eigenvalues): coupled modes with polynomial factors:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/63/1*_fontTm3_eDkTC2yYyG9nA.png" /></figure><ul><li><strong>Stability</strong>: The stability of a linear system is decided by the real parts of its eigenvalues:</li><li><em>If all eigenvalues have negative real parts (Re(λ)&lt;0), every mode in the system decays to zero over time — the system is asymptotically stable (it settles to rest).</em></li><li><em>If any eigenvalue has a positive real part, the corresponding mode grows exponentially — the system is unstable and its state will “explode.”</em></li><li><strong>Transient overshoot</strong>: caused by polynomial terms that initially grow before exponential dominates.​</li><li><strong>Dominant time scales</strong>: inverse of eigenvalue real parts. Fast-decaying modes (large negative Re(λ)) disappear quickly; Engineers use this to predict settling time and design controllers: to control or stabilize a system quickly, all dominant eigenvalues must be shifted to have large negative real parts.</li></ul><h3>A Worked Example: 3×3 Defective System</h3><p>Let’s work through a concrete example to see Jordan form in action. Consider the system matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*6DTHMnQ-_id7QvTrCo8i7g.png" /></figure><p><strong>Step 1: Find eigenvalues</strong></p><p>The characteristic polynomial is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*cPmutA2slqxIju7LZcSGeQ.png" /></figure><p>giving eigenvalues:</p><ul><li>λ1=−1 (appears twice)</li><li>λ2=−2 (appears once)</li></ul><p><strong>Step 2: Check multiplicities</strong></p><p>For λ1=−1:</p><ul><li>Algebraic multiplicity: m_a = 2</li><li>Geometric multiplicity: Solve (A−(−1)I)v=0:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*6N7slIzZXh92WljV-ZU4FA.png" /></figure><p>Only one independent eigenvector, so m_g = 1 &lt; m_a = 2. <strong>Defective!</strong></p><p>For λ2=−2:</p><ul><li>Algebraic multiplicity: m_a = 1</li><li>One independent eigenvector exists, so m_g = 1 = m_a. <strong>Not defective.</strong></li></ul><p><strong>Step 3: Build Jordan chain for λ₁ = -1</strong></p><p>We have eigenvector v1=[1 0 0]. Find generalized eigenvector by solving:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*3CjKMqxqnROpH39dHI1OKg.png" /></figure><p>This gives v2=[0 1 0] (among other solutions).</p><p>For λ2=−2, find eigenvector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*FlxcoqkE3YQ821tzJBLW9w.png" /></figure><p><strong>Step 4: Construct P and J</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*mZXrXq3QM1Rp9xvB3acOCQ.png" /></figure><p>The Jordan form has:</p><ul><li>One 2×2 Jordan block for λ=−1 (defective eigenvalue)</li><li>One 1×1 Jordan block for λ=−2 (non-defective)</li></ul><p><strong>Step 5: Compute e^{Jt}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*MCq2B_amWsSdLByJ1D0Q4w.png" /></figure><p><strong>Step 6: Full solution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*TXiM0O3O6UwjkIbG6pYoQw.png" /></figure><p><strong>Step 7: Engineering interpretation</strong></p><ol><li><strong>Stability</strong>: All eigenvalues have negative real parts (−1 and −2), so the system is <strong>asymptotically stable</strong> — all trajectories decay to zero.</li><li><strong>Three distinct modes</strong>:</li></ol><ul><li><strong>Mode 1</strong> (λ=−1, coupled): decays as e^{-t} with coupling term t*e^{-t}</li><li><strong>Mode 2</strong> (λ=−1, coupled): decays as e^{-t}</li><li><strong>Mode 3</strong> (λ=−2, independent): decays as e^{-2t}, faster than modes 1–2</li></ul><p>3. <strong>Transient behavior</strong>: The term te^{-t} from the 2×2 Jordan block initially grows (when t&lt;1) before decaying. This can cause <strong>overshoot</strong> in the response even though the system is stable.</p><p>4.<strong> Dominant time scale</strong>: Early behavior dominated by fast mode (e^{-2t}, decays in ~1.5 time units), but later behavior dominated by slow coupled modes (e^{-t} and te^{-t}, decay in ~3–5 time units).</p><p>5.<strong> Coupling structure</strong>: States 1 and 2 are coupled (cannot be separated), while state 3 is independent.</p><h3>Why Jordan Form Matters for Engineers</h3><p>Jordan form provides engineers with a systematic framework to answer critical design questions:</p><h3>1. Stability Analysis</h3><p>By examining eigenvalues, you immediately know if the system is stable (all Re(λ)&lt;0), unstable (any Re(λ)&gt;0), or marginally stable. The Jordan block structure tells you if there are polynomial growth terms that might cause unexpected transient behavior.​</p><h3>2. Time-Scale Separation</h3><p>Different eigenvalues correspond to different time scales. Fast modes (large ∣λ∣) settle quickly; slow modes (small ∣λ∣) dominate long-term behavior​. This tells you where to focus control effort and what bandwidth your actuators need.</p><h3>3. Modal Coupling and Controllability</h3><p>The size of Jordan blocks reveals which modes are fundamentally coupled and cannot be controlled independently. A large Jordan block indicates states that must be controlled together.​</p><h3>4. Resonance and Oscillation</h3><p>Complex eigenvalues reveal natural oscillation frequencies. Engineers designing control systems must avoid exciting these frequencies to prevent resonance.​</p><h3>5. Simplified Simulation</h3><p>Computing e^{At} directly is computationally expensive for large n. Using Jordan form, you compute e^{Jt} (much simpler because of block structure) and transform back. This accelerates long-time simulations.​</p><h3>6. Controller Design</h3><p>Many control design methods (pole placement, LQR, observers) rely on understanding the modal structure. Jordan form makes this structure explicit and guides where to place feedback gains.​</p><h3>7. System Diagnosis</h3><p>When a physical system exhibits unexpected behavior — overshoot, slow settling, oscillations — Jordan form helps diagnose the root cause by revealing the underlying modal structure and coupling.</p><h3>Connecting Back to the Shear Example</h3><p>Remember our 2D shear matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*0ov83IDhqvdOKECXRY_1Fg.png" /></figure><p>This is already in Jordan form! It has a single 2×2 Jordan block with eigenvalue λ=1. The “1” in the upper-right position A_12 is not arbitrary coupling — it’s the <strong>minimal necessary coupling</strong> that cannot be eliminated by any coordinate transformation because the matrix is defective.</p><p>The time evolution is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*rB9g_8J4HPHLZitazq6Hzg.png" /></figure><p>The term t*e^t represents exponential growth accelerated by a linear time factor — this is the signature of the Jordan chain. If this were a physical system with eigenvalue 1 (unstable), it wouldn’t just grow exponentially; the coupling would cause even faster polynomial-accelerated growth.</p><h3>Conclusion: From Chaos to Clarity</h3><p>We started with messy state matrices that emerge naturally from physical systems but hide the system’s true behavior. Through the systematic Jordan form procedure — finding eigenvalues, checking multiplicities, building Jordan chains, and constructing the canonical form — we transform this chaos into clarity.</p><p>The Jordan form reveals the <strong>modal architecture</strong> of your system: which modes are independent pure frequencies, which are coupled families that influence each other, where the natural time scales lie, and whether stability is guaranteed or polynomial terms will cause transient mischief.</p><p>For engineers designing, analyzing, or controlling dynamical systems, Jordan form is not just mathematical formalism — it’s a lens that brings the hidden structure of complex dynamics into sharp focus, enabling informed decisions about stability, performance, and control strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63174a1f5581" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Doctor’s Dilemma: How my Professor Made Bayesian Decision Theory Click]]></title>
            <link>https://medium.com/@siddharthramasushil/the-doctors-dilemma-how-my-professor-made-bayesian-decision-theory-click-66d1878a7250?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/66d1878a7250</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 06:21:01 GMT</pubDate>
            <atom:updated>2025-10-12T06:24:46.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*3U6YPy8-Ri6pzxzl.jpeg" /></figure><p>Every time you scroll through Instagram, your phone is making thousands of decisions about what to show you next. When Netflix suggests your next binge-worthy series, when your email automatically sorts spam from important messages — sophisticated algorithms are working behind the scenes using principles you might not even realise exist. This invisible decision-making process is called <strong>statistical learning</strong>, and at its core lies a powerful framework known as Bayesian Decision Theory (BDT).</p><p>In my ECE271A class at UC San Diego, Professor Nuno Vasconcelos used a brilliant analogy that made this complex mathematical framework suddenly crystal clear. Instead of diving straight into abstract formulas and theoretical concepts that often intimidate students, he painted a picture that anyone could understand — regardless of their mathematical background. Let me share that same analogy with you, but with the depth and detail that truly illuminates why this framework is so powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*w5C5ZYyhB_M0BZDv.png" /></figure><h3>The Doctor’s Dilemma: A Complete Guide to Bayesian Decision Theory</h3><p>Imagine you are a doctor working in a busy clinic. It’s Monday morning, and a patient walks into your office presenting with a specific symptom. Your goal is to make the best possible diagnosis — not just any diagnosis, but the one that leads to the best outcome for your patient. This seemingly simple scenario contains all the core components of Bayesian Decision Theory, and more importantly, it mirrors the exact challenges that every AI system faces when making decisions.</p><p>Let’s set up our scenario more precisely:</p><p><strong>State of the World (Y)</strong>: The true, but hidden, illness the patient actually has. In our simplified world, let’s say there are two possibilities:</p><p>Y ∈ {Common Cold, Exotic Flu}.</p><p>In reality, this could be any number of diseases, but two possibilities help us understand the principles clearly.</p><p><strong>Observation (X)</strong>: The observable evidence or symptom that you can actually see or measure. Let’s say the patient presents with “Purple Spots”: X = Purple Spots.</p><p>This is your data — the only concrete information you have to work with.</p><p>The fundamental challenge is clear: you must use the observation (X) to make the best possible inference about the hidden state (Y). You cannot directly observe what disease the patient has — you can only observe the symptoms and use your medical knowledge to make the best possible decision.</p><p>This is exactly the same challenge faced by every machine learning algorithm: using observable data to make inferences about hidden or unobservable states of the world.</p><h3>Ingredient 1: The Prior Probability (Your Initial Belief Before Seeing Evidence)</h3><p><strong>What it really is</strong>: The prior probability represents your background knowledge about the world before you encounter any specific evidence. It’s your starting point — what you believe about the relative frequency or likelihood of different states based on your general experience and knowledge.</p><p><strong>The Mathematical Formula</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/70/1*Y9M0h0QNSX220hubrM5qBw.png" /></figure><p>This deceptively simple notation reads as “the probability that the state of the world is y,” but there’s much more depth here than meets the eye.</p><p><strong>Where do priors come from?</strong> In our medical analogy, your priors come from several sources:</p><ul><li><strong>Medical school training</strong>: You learned that certain diseases are more common than others</li><li><strong>Clinical experience</strong>: You’ve seen hundreds of patients and noticed patterns</li><li><strong>Epidemiological data</strong>: Public health statistics tell you about disease prevalence in your region</li><li><strong>Seasonal factors</strong>: Some illnesses are more common at certain times of year</li><li><strong>Patient demographics</strong>: Age, location, and other factors influence disease probability</li></ul><p>In our specific example:</p><ul><li>PY(Common Cold)=0.99 (Extremely high)</li><li>PY(Exotic Flu)=0.0001(Extremely low)</li></ul><p><strong>Why this matters</strong>: You know from your years of practice that the common cold affects millions of people every year, while exotic flu is extraordinarily rare — perhaps affecting only a few hundred people globally. This isn’t just a guess; it’s informed knowledge based on real-world data.</p><p><strong>The power and controversy of priors</strong>: Priors are both the strength and the potential weakness of Bayesian methods. They allow you to incorporate valuable background knowledge, but they can also introduce bias. A doctor who has never seen exotic flu might set the prior too low, while a specialist in tropical diseases might set it higher based on their experience.</p><h3>Ingredient 2: The Likelihood (The Bridge Between Cause and Effect)</h3><p><strong>What it really represents</strong>: The likelihood is perhaps the most crucial component of Bayesian reasoning, yet it’s often the most misunderstood. It tells you how well each potential cause (disease) explains the observed effect (symptom). Critically, it answers the forward question: “If I knew for certain that the patient had this specific disease, what is the probability they would exhibit this particular symptom?”</p><p><strong>The Mathematical Formula</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*GKm6wVKUDfUZGL20h-1tpg.png" /></figure><p>This reads as “the probability of observing x given that the true state is y,” but let’s dive much deeper into what this means.</p><p><strong>The direction of causation</strong>: This is absolutely crucial to understand. The likelihood goes from cause to effect, from disease to symptom. You’re not asking “What’s the probability the patient has exotic flu given that they have purple spots?” — that’s what you’re trying to figure out. Instead, you’re asking “What’s the probability a patient would have purple spots if they definitely had exotic flu?”</p><p><strong>Where likelihood comes from</strong>: In our medical scenario, likelihood comes from:</p><ul><li><strong>Medical literature</strong>: Published studies on how diseases manifest</li><li><strong>Clinical trials</strong>: Controlled studies of symptoms in confirmed cases</li><li><strong>Pathophysiology</strong>: Understanding of how diseases affect the body</li><li><strong>Your own clinical observations</strong>: Patterns you’ve noticed in confirmed cases</li></ul><p>In our example:</p><ul><li>PX∣Y(Purple Spots∣Exotic Flu)=0.9: If a patient definitely has exotic flu, there’s a 90% chance they’ll develop purple spots. This high likelihood makes purple spots a strong indicator of exotic flu.</li><li>PX∣Y(Purple Spots∣Common Cold)=0: Purple spots never occur with common colds. This zero likelihood is powerful information.</li></ul><p><strong>Why this asymmetry matters</strong>: Notice the dramatic difference in these likelihoods. While exotic flu is extremely rare (low prior), it strongly predicts purple spots when present (high likelihood). Conversely, common cold is very common (high prior) but cannot explain the observed symptom (zero likelihood).</p><p><strong>The discriminative power</strong>: Good diagnostic tests or features have very different likelihoods for different conditions. If both diseases caused purple spots equally often, the symptom would be useless for diagnosis. The large difference in likelihoods (0.9 vs 0.0) gives this symptom strong discriminative power.</p><h3>The Engine: Bayes’ Rule (The Mathematical Heart of Learning)</h3><p><strong>What it really accomplishes</strong>: Bayes’ Rule is the mathematical engine that takes your background knowledge (prior) and combines it with new evidence (likelihood) to produce an updated, more informed belief (posterior). It’s literally the mathematics of learning from experience.</p><p><strong>The Complete Formula</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*kbYhzsrIjl6RwmlqCkKM6Q.png" /></figure><p>Let’s break down each component with the depth it deserves:</p><p><strong>P Y∣X(y∣x)— The Posterior (Your Updated Belief)</strong><br> This is your ultimate goal — the probability of each disease given that you’ve observed the symptom. It represents your refined, evidence-based belief after incorporating new information. This is what you’ll use to make your decision.</p><p><strong>P X∣Y(x∣y)— The Likelihood (How Well Each Cause Explains the Effect)</strong><br> As we discussed extensively above, this captures how probable the observed evidence is under each possible explanation.</p><p><strong>P Y(y) — The Prior (Your Background Knowledge)</strong><br> Your starting belief before seeing the symptom, based on general knowledge about disease prevalence.</p><p><strong>PX(x)— The Evidence (The Normalizing Factor)</strong><br> This represents the total probability of observing the symptom across all possible causes. Mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*HZ5lnkke9ou8imH8zvpGhw.png" /></figure><p>In our case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*KIBp-PDN0S-2aiKx5InFXw.png" /></figure><p><strong>Let’s calculate the posteriors step by step</strong>:</p><p>For Exotic Flu:<br> P Y∣X(Exotic Flu∣Purple Spots)</p><p>=0.9×0.00010/00009=0.00009</p><p>For Common Cold:<br> P Y∣X(Common Cold∣Purple Spots)</p><p>=0×0.990/00009=0</p><p><strong>The remarkable result</strong>: Despite exotic flu being extraordinarily rare (0.01% prior probability), observing purple spots completely flips your belief. The posterior probability of exotic flu becomes 100%! This demonstrates the power of discriminative evidence to overcome strong priors.</p><p><strong>The intuition</strong>: Bayes’ Rule is performing a sophisticated balancing act. It asks: “Given what I know about the world in general (prior) and given how well each explanation fits this specific observation (likelihood), what should I now believe?” The mathematics ensures this combination is optimal in a precise sense.</p><h3>Ingredient 3: The Loss Function (Quantifying the Cost of Being Wrong)</h3><p><strong>What it really captures</strong>: The loss function is where Bayesian Decision Theory becomes truly practical. It recognizes a fundamental reality: in the real world, not all mistakes are created equal. Some errors are minor inconveniences, while others can be catastrophic.</p><p><strong>The Mathematical Representation</strong>: L(decision,truth)</p><p>This reads as “the loss incurred when you make a specific decision, and the actual truth turns out to be something else.”</p><p><strong>Why loss functions matter</strong>: Pure probability tells you what’s most likely to be true, but optimal decision-making requires understanding the consequences of being wrong. A decision that’s slightly less probable might still be better if the cost of missing it is enormous.</p><p><strong>In our medical scenario</strong>, let’s think carefully about the consequences:</p><ul><li>L(decide ’Cold’,truth ’Flu’)=1000: You send a patient with exotic flu home with cough drops. They could die from lack of proper treatment. This is a catastrophic error with enormous human and legal consequences.</li><li>L(decide ’Flu’,truth ’Cold’)=50: You treat a common cold with expensive exotic flu treatment. The patient recovers (they would have anyway), but you’ve wasted resources and possibly caused unnecessary side effects. This is costly but not catastrophic.</li><li>L(decide ’Cold’,truth ’Cold’)=0: Correct diagnosis and treatment. No loss.</li><li>L(decide ’Flu’,truth ’Flu’)=0: Correct diagnosis and treatment. No loss.</li></ul><p><strong>The asymmetry is crucial</strong>: Notice that the loss for missing exotic flu (1000) is twenty times greater than the loss for over-treating a cold (50). This reflects the medical principle that it’s often better to err on the side of caution when serious conditions are possible.</p><p><strong>Different scenarios, different loss functions</strong>:</p><ul><li>In military applications, missing a threat might have infinite loss</li><li>In spam filtering, blocking important emails might be worse than letting some spam through</li><li>In medical screening, false negatives (missing disease) are usually worse than false positives (unnecessary worry)</li><li>In loan approval, false positives (approving bad loans) might be worse than false negatives (rejecting good customers)</li></ul><p><strong>Domain expertise matters</strong>: Defining appropriate loss functions requires deep understanding of the domain. This is where human expertise becomes crucial in designing AI systems — the mathematics can optimize decisions, but humans must define what “optimal” means.</p><h3>The Goal: Minimizing Expected Risk (The Mathematics of Optimal Decision-Making)</h3><p><strong>What risk really means</strong>: Risk, in Bayesian decision theory, is the expected loss associated with any decision. It’s not just the worst-case scenario, but the average loss you’d experience if you made the same decision repeatedly under similar circumstances.</p><p><strong>The Mathematical Definition</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*nJqurPsN2XsnAgK4BfA4mw.png" /></figure><p>This formula captures a profound idea: the risk of any decision is the weighted average of all possible losses, where the weights are how likely each outcome is to be true.</p><p><strong>Let’s calculate the risk for each possible decision in our scenario</strong>:</p><p><strong>Risk of deciding “Common Cold”</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*jc_gPkmlV0KrkFrKyq7Xhw.png" /></figure><p><strong>Risk of deciding “Exotic Flu”</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*U_scJtUI3j_a7ikjOU26Gg.png" /></figure><p><strong>The clear winner</strong>: Deciding on exotic flu has zero expected risk, while deciding on common cold has an expected risk of 1000. The choice is obvious.</p><p><strong>Why this framework is powerful</strong>: Expected risk combines three crucial elements:</p><ol><li><strong>Uncertainty</strong> (captured by posterior probabilities)</li><li><strong>Evidence</strong> (incorporated through Bayes’ rule)</li><li><strong>Consequences</strong> (quantified by the loss function)</li></ol><p>This combination ensures that decisions account for both what’s likely to be true and what happens if you’re wrong.</p><h3>The Master Rule: The Bayes Decision Rule (The Guarantee of Optimality)</h3><p><strong>What it guarantees</strong>: The Bayes Decision Rule provides a mathematical guarantee: if you follow this rule consistently, you will achieve the lowest possible average loss over time. No other decision-making strategy can do better in the long run.</p><p><strong>The Mathematical Statement</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ISzQqhcfWLfsbM8ARGgy5Q.png" /></figure><p>This reads: “The optimal decision g∗(x) is whichever decision minimizes the conditional risk.”</p><p><strong>Why this is profound</strong>: This isn’t just a good heuristic or a reasonable approach — it’s mathematically proven to be optimal. If you’re making decisions under uncertainty and you can specify your loss function and model the probabilities correctly, Bayes Decision Theory tells you exactly what to do.</p><p><strong>The process</strong>:</p><ol><li>For each possible decision you could make</li><li>Calculate the expected risk of that decision</li><li>Choose the decision with the minimum expected risk</li></ol><p><strong>In our example</strong>: We calculated that deciding “Exotic Flu” has risk 0, while deciding “Common Cold” has risk 1000. Therefore, g∗(Purple Spots)=Exotic Flu</p><p><strong>The beauty of generality</strong>: This same framework works whether you’re diagnosing diseases, filtering spam, recommending products, or making any other decision under uncertainty. The mathematics remains the same; only the specifics of the probabilities and loss functions change.</p><h3>The Simplified Case: Minimum Probability of Error (When All Mistakes Are Equal)</h3><p><strong>When to use this simplification</strong>: Often in homework problems, exams, or simplified scenarios, you’re asked to find the “minimum probability of error” rule. This corresponds to a special case where all correct decisions have the same value, and all incorrect decisions have the same cost.</p><p><strong>The 0–1 Loss Function</strong>:</p><ul><li>L(correct decision)=0 for any correct diagnosis</li><li>L(incorrect decision)= 1 for any incorrect diagnosis</li></ul><p><strong>Why this simplification matters</strong>: When all errors are equally bad, you don’t need to worry about the specific costs of different mistakes. You just want to be right as often as possible.</p><p><strong>The Maximum A-Posteriori (MAP) Rule</strong>: In this special case, the Bayes Decision Rule simplifies dramatically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*ClR3SWQ_uCxLI7wrv7lb1A.png" /></figure><p>This says: “Just pick whichever class has the highest posterior probability.”</p><p><strong>Further simplification</strong>: Since the denominator in Bayes’ rule (P_X(x)) is the same for all classes, you can ignore it when comparing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*PfqXTR0QKVrbnSfy7TQWQw.png" /></figure><p>This gives us the practical rule: “Multiply the likelihood by the prior for each class, and pick the class that gives the biggest number.”</p><p><strong>In our example</strong>:</p><ul><li>For Exotic Flu: PX∣Y(Purple Spots∣Exotic Flu)×PY(Exotic Flu)=0.9×0.0001=0.00009</li><li>For Common Cold: PX∣Y(Purple Spots∣Common Cold)×PY(Common Cold)=0×0.99=0</li></ul><p>The MAP rule would choose Exotic Flu, which matches our more detailed analysis.</p><h3>Why This Framework Powers Our Digital World</h3><p>Now that you understand the doctor’s dilemma in complete detail, you can see these same principles operating everywhere in your digital life, but with much more sophistication and scale.</p><p><strong>Instagram’s Feed Algorithm</strong>: When Instagram decides which posts to show you, it’s essentially performing thousands of medical diagnoses per second. The “symptoms” are your past behavior — likes, comments, time spent viewing, sharing patterns. The “diseases” are different types of content that might engage you — friend updates, sponsored posts, trending content, etc. The algorithm has priors about what content generally performs well, likelihoods about how users with your profile typically respond to different content types, and a loss function that heavily penalizes showing you content that makes you leave the platform.</p><p><strong>Autonomous Vehicles</strong>: Self-driving cars constantly make Bayesian decisions about the world around them. Is that object in the road a plastic bag (low risk) or a child (catastrophic risk)? The sensor readings are the “symptoms,” the possible objects are the “diseases,” and the loss function heavily weights avoiding harm to humans.</p><p><strong>Financial Fraud Detection</strong>: Banks use these principles to identify fraudulent transactions. Your normal spending patterns establish priors and likelihoods, while unusual transactions trigger the diagnostic process. The loss function balances customer inconvenience (blocking legitimate transactions) against financial losses (allowing fraud).</p><h3>The Deeper Insights</h3><p>The beauty of understanding these principles deeply is that you can now see the mathematical structure underlying many AI systems that might have seemed mysterious before. Every time a machine makes a decision under uncertainty, chances are it’s using some form of Bayesian reasoning, even if it’s not explicitly framed that way.</p><p>The next time you interact with an intelligent system — whether it’s getting a personalized recommendation, having your photo automatically tagged, or benefiting from medical AI — you’ll understand the elegant mathematical principles working behind the scenes. And thanks to Professor Vasconcelos’s brilliant analogy, what once seemed like impenetrable mathematics now feels as natural as a doctor making a diagnosis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66d1878a7250" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SVD in robotics: low-rank approximation]]></title>
            <link>https://medium.com/@siddharthramasushil/svd-in-robotics-low-rank-approximation-cc6efe0f6a36?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc6efe0f6a36</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 00:32:45 GMT</pubDate>
            <atom:updated>2025-09-27T00:32:45.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*PsMz0Bp697QEuY5gqejkkA.png" /></figure><h3>The Missing Piece: Understanding the Outer Product</h3><p>You already know the Singular Value Decomposition (SVD) takes your complex data matrix, A, and breaks it down into simple, ranked pieces. Before we dive deeper into that sum, let’s understand the fundamental building block: the <strong>outer product</strong>.</p><p>In standard multiplication, a <strong>dot product</strong> (or inner product) takes two vectors and results in a single number (a scalar).</p><p>Dot Product: v⊤u=scalar</p><p>The <strong>outer product</strong> does the opposite: it takes two vectors and produces a <strong>matrix</strong>. It’s formed by multiplying a column vector by a row vector.</p><p>Outer Product: uv⊤=M</p><p>where M is a matrix.</p><p>The crucial property of an outer product formed by two non-zero vectors is that the resulting matrix, M, always has a <strong>rank of 1</strong>. This is the <strong>simplest possible non-zero matrix</strong>. Think of it as a single, pure, undiluted pattern.</p><h3>From Product Form to the Powerful Sum</h3><p>The product form of SVD is elegant: A=UΣV⊤.</p><ol><li><strong>U and V:</strong> These matrices hold the <strong>singular vectors</strong>. The columns of U (u1​,u2​,…) are the <strong>left singular vectors</strong>, and the columns of V (v1​,v2​,…) are the <strong>right singular vectors</strong>. They are the independent basis vectors (like axes) that define the “directions” of the data patterns.</li><li><strong>Σ:</strong> This diagonal matrix holds the <strong>singular values</strong> (σ1​,σ2​,…) along its diagonal.</li></ol><p>When you perform the matrix multiplication of UΣV⊤, the structure of matrix algebra <em>naturally</em> expands into the sum of weighted outer products:</p><p>A=σ1​(u1​v1⊤​)+σ2​(u2​v2⊤​)+⋯+σr​(ur​vr⊤​)</p><p>Each term in the sum is a <strong>rank-1 matrix</strong> (the outer product of a left and right singular vector) scaled by its corresponding singular value.</p><h3>What the Singular Value (σi​) Really Signifies</h3><p>In this decomposition, the <strong>singular values (σi​) are the keys to the kingdom</strong>. They are:</p><h4>1. The Measure of Importance (The “Weight”)</h4><p>Since the singular values are always sorted descendingly (σ1​≥σ2​≥…), σ1​ is the largest. This means the first term, σ1​u1​v1⊤​, is the <strong>most significant, dominant pattern</strong> or “mode” in the entire data set A.</p><ul><li><strong>σ1​ is King:</strong> The first term captures the most variance (the most structure) in your data. In robotics, if A is a trajectory matrix, the first term often represents the mean movement or the most common pattern.</li><li><strong>Decay:</strong> The values decay quickly. A large drop-off after the k-th value tells you that the remaining terms are likely negligible (or just noise).</li></ul><h4>2. The Scale Factor (The “Stretching”)</h4><p>Geometrically, SVD can be viewed as taking a sphere, rotating it (by V⊤), <strong>stretching it along the principal axes</strong> (by Σ), and then rotating it again (by U). The singular values are the <strong>scale factors</strong> that define how much stretching occurs in each direction.</p><p>A large σi​ means the data spreads out significantly along the direction defined by ui​ and vi​.</p><h3>The Power of Truncation (Low-Rank Approximation)</h3><p>This weighted sum gives us the power of <strong>low-rank approximation</strong>.</p><p>If we want the best representation of A using only k patterns, we simply <strong>truncate the sum</strong> after the k-th term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*WVlrjjNACaolKUj-9iEuuA.jpeg" /></figure><p>This Ak​ is the mathematically proven <strong>closest possible rank-k matrix</strong> to A. This is why SVD is so critical in robotics:</p><ul><li><strong>Noise Reduction:</strong> If you have noisy sensor data, truncating the small, tail-end singular values essentially <strong>filters out the noise</strong> which often hides in the least-important components.</li><li><strong>Data Compression:</strong> Instead of storing the large matrix A, you only need to store the first few singular values, σ1​ through σk​, and the corresponding singular vectors, u1​ through uk​ and v1​ through vk​. This is a massive saving in memory and computation for large models or maps.</li></ul><h3>How Robotics Uses This Atomic Decomposition</h3><ul><li>Visual SLAM &amp; Structure from Motion: The observation matrix from multiple camera frames is decomposed by SVD; only the top three terms matter for 3D geometry.</li><li>Essential Matrix Estimation: SVD’s sum-of-outer-products helps project matrices onto their physically valid space, removing errors.</li><li>Sensor Fusion &amp; Compression: Recording and operating on large sensor matrices becomes feasible with SVD truncation — drastically reduces computational load.</li><li>Anomaly/Pattern Detection: Detect dominant modes (normal behavior) or flag outliers (failures or new events) by inspecting leading outer product terms.</li></ul><h3>Concrete Example: Cleaning a Noisy Trajectory</h3><p>Suppose you’re mapping a robot’s 2D movement through time: columns represent <em>x</em> and y, rows represent time frames.</p><ul><li>Noise in odometry blurs the true path.</li><li>SVD expansion breaks this “noisy map” into ranked outer products — dominant terms reflect actual patterns (e.g., forward movement), weaker ones are likely noise and can be dropped.</li><li>Reconstructed path (using first <em>k</em> terms) is less noisy, computationally efficient, and easier to analyze.</li></ul><h3>Intuitive Takeaway and Final Notes</h3><p>See every data matrix as a ranked “library” of pure patterns:</p><ul><li>The sum-of-outer-products view reveals the atomic patterns in your robot’s world — each ready for selection, denoising, or compression.</li><li>In robotics, this interpretation transforms SVD from a mere matrix factorization into a practical, powerful tool for building robust, efficient systems.</li></ul><p>Next time you use SVD in robotics, remember — the real magic is in how it slices your data into ranked, interpretable outer products, each a stepping stone for reliable perception, mapping, and action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc6efe0f6a36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands on SLAM Frontend: Landmark Lifecycle]]></title>
            <link>https://medium.com/@siddharthramasushil/hands-on-slam-frontend-part-2-d16ba9902987?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/d16ba9902987</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[aml]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 23:27:11 GMT</pubDate>
            <atom:updated>2025-09-23T06:55:06.521Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In Part 1, I walked through my early experiments with feature detection, matching, and triangulation. I asked a question: if triangulation works so well, why not just keep doing it forever between consecutive frames? Today, we dive into why that approach fundamentally misses the point of SLAM.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*7BW4NTj1K8x4CXoF.gif" /></figure><h3>Why More Isn’t Always Better</h3><p>Remember that question from Part 1? Why not just triangulate between every consecutive pair of frames?</p><p>Initially, this seemed like the obvious approach. Frame 1–2: triangulate, get 3D points. Frame 2–3: triangulate more points. Frame 3–4: even more points. I’d build the most complete 3D map anyone had ever seen!</p><p>But before I even wrote a single line of code for this approach, I realized the fundamental flaw: each triangulation creates its own coordinate system.</p><p>Think about it carefully. When you triangulate between frames 1–2, you arbitrarily place frame 1 at the origin and compute frame 2’s relative pose. When you triangulate between frames 2–3, you’d place frame 2 at the origin for that computation. The 3D points from triangulation 1–2 live in a completely different coordinate system than the points from triangulation 2–3.</p><p>You’re not building one coherent world — you’re building dozens of disconnected world fragments. A single street corner would exist as multiple different 3D points, each in its own coordinate system, with no way to know they represent the same physical feature.</p><p>Triangulation gives you geometry, but not necessarily the <em>same</em> geometry. Each frame pair creates its own coordinate system. Without a way to align these systems, you’re building parallel universes, not a unified map.</p><p>This realization led me to the core insight that separates real SLAM from naive approaches: you need persistent landmarks in a single, consistent coordinate system.</p><h3>From Geometry to Tracking</h3><p>The solution became clear once I understood the problem. SLAM isn’t about constantly creating new geometry — it’s about creating geometry once, then tracking against it.</p><p>The proper architecture flows like this:</p><p>Initialization Phase:</p><ol><li>Take two well-separated frames</li><li>Triangulate to create initial 3D landmarks</li><li>Establish the coordinate system (arbitrary but consistent)</li><li>This becomes your “world” reference frame</li></ol><p>Tracking Phase:</p><ol><li>For each new frame, find correspondences with existing landmarks</li><li>Use PnP to determine camera pose in the established world frame</li><li>Add new landmarks only when necessary (keyframes)</li><li>Always maintain consistency with the original coordinate system</li></ol><p>This shift in thinking was profound. Instead of asking “how do I create more 3D points?” I started asking “how do I maintain consistent tracking against existing 3D points?”</p><h3>The Feature vs. Landmark Confusion: A Critical Distinction</h3><p>Before diving deeper into landmark association, I need to address a confusion: the difference between matched features and landmarks. I kept using these terms interchangeably, but they represent fundamentally different concepts.</p><p>A matched feature is ephemeral — it’s just a correspondence between observations in different frames, like saying “this corner in frame 10 looks similar to that corner in frame 15.” It exists only for the duration of that comparison and tells you nothing about the world.</p><p>A landmark, however, is persistent — it’s a confirmed 3D point that represents an actual physical location in the world. When I match features, I’m finding candidates. When I create landmarks, I’m making commitments about the structure of reality. The feature matching process is just an intermediate step; the real goal is to either re-observe existing landmarks or promote reliable features to become new landmarks in my permanent map. This distinction became crucial because I realized I wasn’t just tracking pixel correspondences across frames — I was building a persistent model of 3D space that needed to outlive any individual observation.</p><h3>PnP and Pose Tracking: The New Foundation</h3><p>Time for the big leagues: pose estimation. Given that I know where some 3D landmarks are, and I can see them in my current image, where must my camera be?</p><p>This is called the Perspective-n-Point (PnP) problem, and conceptually it’s beautiful: if you have a set of 3D points and their corresponding 2D projections in your current frame, you can work backwards to find the camera pose that would produce exactly those projections.</p><p>The mathematical core involves minimizing reprojection error — finding the camera position and orientation that makes the predicted pixel locations match the observed pixel locations as closely as possible.</p><p>But the real challenge isn’t the math — it’s the data management. How do you maintain reliable correspondences between 3D landmarks and 2D observations across dozens or hundreds of frames?</p><p>I fed my triangulated 3D points and their corresponding 2D observations into the PnP solver. My first trajectory looked… well, it looked like someone having a seizure while drawing a map.</p><p>The camera was jumping all over the place, sometimes teleporting meters between frames. Sometimes it decided it was underground. Other times it was flying.</p><p>lesson:</p><p>PnP is only as good as your input data. Feed it bad 3D points (which triangulation loves to give you), and you get bad poses. Feed it bad correspondences (which feature matching loves to give you), and you get garbage.</p><p>The robustness came from RANSAC — trying different subsets of correspondences, finding the ones that agreed on a pose, and ignoring the outliers. This transformed my seizure-like trajectory into something resembling actual camera motion.</p><p>But even with robust PnP, I faced the deeper challenge: maintaining landmark associations across time.</p><h3>The Landmark Association Problem: The Heart of SLAM</h3><p>Here’s a problem: how do you keep track of the same 3D point across multiple frames?</p><p>This sounds trivial until you think about it carefully. I have a landmark — let’s say it’s a corner of a building. In frame 10, it appears at pixel (245, 180). In frame 15, the same physical corner appears at pixel (289, 195). How do I know these two pixel observations correspond to the same 3D landmark?</p><p>The naive approach is frame-to-frame matching: match features between consecutive frames, and if they match, assume they represent the same landmark. This seems reasonable, but it fails catastrophically because features change appearance as you move. Lighting changes, viewing angles change, parts of features get occluded.</p><p>With this brittle association, landmarks get lost constantly. Even if a landmark is clearly visible and would be useful for pose estimation, you lose it because you can’t maintain the connection across frames.</p><p>I watched my inlier counts collapse systematically:</p><ul><li>Frame 10: 87 inliers</li><li>Frame 15: 62 inliers</li><li>Frame 20: 41 inliers</li><li>Frame 25: 23 inliers</li><li>Frame 30: 8 inliers — TRACKING LOST</li></ul><p>lesson:</p><p>In SLAM, you’re not just tracking features — you’re maintaining a persistent map of landmarks. Losing landmarks means losing your ability to localize.</p><h3>Map-to-Frame Reprojection: The Breakthrough</h3><p>The solution that saved this issue was map-to-frame reprojection matching. Instead of only matching against previous frames, actively search for all known landmarks in each new frame.</p><p>The process is conceptually elegant:</p><ol><li>Take your current pose estimate</li><li>For each landmark in your map, project it into the current image using camera geometry</li><li>If it projects inside the image bounds, search for a matching feature nearby</li><li>If you find one, re-associate that landmark with the current frame</li></ol><p>This architectural change was transformative. Landmarks could now survive across many frames, not just consecutive ones. A landmark that disappeared for a few frames could come back when the viewpoint became favorable again. My inlier counts stabilized, and tracking became much more robust.</p><p>But this also revealed new architectural challenges. The computational complexity increased significantly — you’re now testing every landmark against every frame. And you need a good pose estimate to do accurate projection.</p><h3>Keyframes: Strategic Memory Management</h3><p>The landmark association problem forced me to think carefully about memory management. You can’t keep every single frame — that’s computationally prohibitive and mostly redundant. But you also can’t just keep the last frame, because then you lose landmarks too quickly.</p><p>Keyframes became the solution: carefully selected frames that capture the essential structure of the environment. But the selection criteria proved crucial.</p><p>The keyframe decision involves balancing several factors:</p><ul><li>Coverage: Does this frame show new parts of the environment?</li><li>Overlap: Does it maintain sufficient connection with existing keyframes?</li><li>Quality: Are the features well-distributed and trackable?</li><li>Computational cost: Can the system handle another keyframe?</li></ul><p>I developed a multi-criteria decision system: create a new keyframe if the camera moved too far, rotated too much, or if the number of tracked landmarks dropped below a threshold.</p><p>lesson:</p><p>Keyframe selection is about balancing information content with computational cost. You want keyframes that capture new views of the environment without overwhelming your system.</p><h3>The Landmark Lifecycle: Birth, Life, and Death</h3><p>Landmarks aren’t just created once during initialization — they have a complex lifecycle:</p><p>Birth: Landmarks are created during keyframe insertion by triangulating between the new keyframe and previous keyframes.</p><p>Life: During their active period, landmarks are:</p><ul><li>Tracked across multiple frames via reprojection matching</li><li>Used for pose estimation via PnP</li><li>Refined through multiple observations from different viewpoints</li></ul><p>Death: Landmarks eventually become untrackable due to:</p><ul><li>Moving out of the camera’s field of view</li><li>Occlusion by other objects</li><li>Changes in lighting or appearance</li><li>Accumulation of tracking errors</li></ul><p>This lifecycle perspective helped me understand that SLAM systems need active landmark management — not just creating landmarks, but maintaining, refining, and eventually retiring them.</p><h3>The Frontend Architecture: Putting It All Together</h3><p>With all these insights, the complete frontend architecture emerged:</p><p>Frame Processing Pipeline:</p><ol><li>Feature Detection: Find interesting points in the current frame</li><li>Landmark Association: Match current features with known landmarks via reprojection</li><li>Pose Estimation: Use PnP with associated landmarks to estimate camera pose</li><li>Keyframe Decision: Determine if current frame should become a keyframe</li><li>Map Update: If keyframe, triangulate new landmarks and add to map</li><li>Trajectory Update: Record current pose in trajectory</li></ol><p>Data Structures:</p><ul><li>Landmarks: 3D position, descriptor, observation history, quality metrics</li><li>Keyframes: Selected frames with pose, features, and landmark associations</li><li>Trajectory: Time-ordered sequence of camera poses</li><li>Map: Collection of active landmarks with their properties.</li></ul><p>Key Subsystems:</p><ul><li>Matcher: Handles both descriptor-based and reprojection-based matching</li><li>Triangulator: Creates new landmarks from multiple views</li><li>Pose Estimator: Robust PnP with RANSAC for outlier rejection</li><li>Keyframe Manager: Decides when and how to add new keyframes</li></ul><p>This architecture created a beautiful feedback loop: track existing landmarks to estimate pose, use pose estimates to find more landmarks, use additional landmarks to improve pose estimates.</p><p>For the first time, my system felt like coherent SLAM rather than a collection of independent computer vision algorithms.</p><h3>The Persistent Problems</h3><p>No matter how elegant the architecture, certain fundamental problems kept emerging:</p><p>Drift: Even with perfect feature matches, tiny errors in pose estimation accumulate over time. My carefully constructed coordinate system slowly but inexorably diverged from reality.</p><p>Scale Ambiguity: Monocular SLAM can’t determine absolute scale. My reconstruction was geometrically correct but could represent a highway or a tabletop model with equal validity.</p><p>Coordinate System Arbitrariness: My maps were internally consistent but had no relationship to any meaningful reference frame. North could be any direction, up could be sideways.</p><p>Tracking Failures: Sometimes the system would lose all landmarks simultaneously and require complete re-initialization, losing all accumulated knowledge.</p><p>Computational Growth: As the map grew larger, the reprojection matching became increasingly expensive, eventually overwhelming the system.</p><h3>Why Frontend Isn’t Enough: The Mathematical Reality</h3><p>The frontend approach is fundamentally limited.</p><p>The frontend makes local decisions with local information. It asks: “given what I see right now, what’s my best guess for where I am?” But SLAM requires global consistency — ensuring that all poses and landmarks form a coherent, non-contradictory model of the world.</p><p>The mathematical reality is stark: local consistency does not imply global consistency. You can have every individual pose estimate be reasonable while the overall trajectory is nonsensical.</p><p>This insight explained why the advanced SLAM techniques exist:</p><p>Bundle Adjustment addresses the drift problem by simultaneously optimizing all poses and landmarks to minimize global reprojection error.</p><p>Loop Closure handles the memory problem by recognizing when you’ve returned to a previously visited location and enforcing consistency.</p><p>Pose Graph Optimization provides a framework for maintaining global consistency as new information becomes available.</p><h3>The Path Forward</h3><p>My frontend SLAM system will never compete with modern implementations. It’s too limited, too fragile, too architecturally constrained. But it served its purpose: giving me deep, intuitive understanding of why SLAM is structured the way it is.</p><p>Now when I encounter visual-inertial odometry, I understand why IMU integration helps with the scale and drift problems I faced. When I study loop closure detection, I recognize it as the solution to the global consistency issues that haunted my frontend. When I explore bundle adjustment, I see it as the mathematical framework I desperately needed.</p><p>The frontend was my crash course in SLAM architecture. It prepared me to appreciate the sophistication of modern systems, to understand their design choices, and to contribute meaningfully to their advancement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16ba9902987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On SLAM: My Experience Building a Visual Frontend Pipeline]]></title>
            <link>https://medium.com/@siddharthramasushil/frontend-slam-the-essential-struggles-every-beginner-needs-ecca3532e821?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecca3532e821</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 11:09:28 GMT</pubDate>
            <atom:updated>2025-09-03T12:32:08.488Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I Decided to Start with Just the Frontend</h3><p>Picture this: you’re staring at a research paper about SLAM, and there’s this intimidating diagram with boxes labelled “Bundle Adjustment,” “Loop Closure,” “Pose Graph Optimisation.” Your brain immediately goes into overwhelm mode. Where do you even start?</p><p>That’s exactly where I found myself two months ago. Instead of diving headfirst into the deep end of optimization theory; The plan was that I’d build something that could track a camera in real-time, see how it fails, and <em>then</em> I’d understand why all those scary optimization techniques exist. I wanted to feel the pain points myself before reaching for the mathematical hammers.</p><p>I structured my entire journey as mini executable systems that anyone could test from my repository. Each component could run independently — feature detection, matching, triangulation, pose estimation. I wanted to see exactly where things would break, component by component.</p><h3>What is the SLAM Frontend? (Explained Like You’re Human)</h3><p>Imagine you’re walking through your house with your eyes closed, but every few seconds you can open them and take a quick snapshot. From each snapshot, you need to figure out:</p><ol><li>Where am I now? (your position and orientation)</li><li>What can I see? (interesting points in the environment)</li><li>How do these points relate to what I saw before? (correspondences)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*0upCMI2_hqSIxbyKtksMmQ.gif" /></figure><h3>My First Baby Step: Detect + Match</h3><p>I started with what seemed like the easiest part: just detecting features and matching them between two consecutive images. How hard could it be?</p><p>I fired up OpenCV, loaded a KITTI sequence (those famous driving datasets), and wrote my first 50 lines of code:</p><pre>// Detect ORB features<br>detector-&gt;detectAndCompute(img1, Mat(), kp1, desc1);<br>detector-&gt;detectAndCompute(img2, Mat(), kp2, desc2);</pre><pre>// Match them<br>matcher-&gt;match(desc1, desc2, matches);</pre><pre>// Draw pretty lines<br>drawMatches(img1, kp1, img2, kp2, matches, output);</pre><p>The first time I ran it and saw those colorful lines connecting features between frames of my room, I felt like I’d just invented SLAM. “Look at that! My computer can see that this is the same corner in both images!”</p><p>But then I actually looked at the matches. Oh boy.</p><p>About 30% of them were obviously wrong. The algorithm was enthusiastically connecting everything, whether it made sense or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAkgQX-4Emn-oewxFd-l_Q.png" /><figcaption>many matches, includes bad matches</figcaption></figure><p>My first hard lesson: Feature descriptors are just mathematical summaries. They don’t understand semantics. To the algorithm, a dark blob surrounded by lighter pixels might be “similar” whether it’s a car tire or a pothole.</p><p>I spent the next week implementing ratio tests, cross-checking, homography filtering — basically every trick in the book to clean up these matches. The success rate improved, but something bothered me: I was spending more time fighting bad matches than actually building SLAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnrsUP2WOe0FQsdF1QVPog.png" /><figcaption>good matches, but very few (you get the trade off)</figcaption></figure><p>This was my first taste of what would become a recurring theme: the frontend is fragile, and you spend most of your time dealing with edge cases rather than building the core functionality.</p><h3>From Matching to Geometry: Triangulation</h3><p>After getting decent matches, I was ready for the next step: triangulation— where 2D pixels become 3D understanding.</p><h3>How Triangulation Actually Works</h3><p>Input from the previous modules: I get matched feature pairs from my detector and matcher. Each match gives me two pixel coordinates — the same physical point seen from two different camera positions. For example, a corner of a building might be at pixel (245, 180) in frame 1 and pixel (289, 195) in frame 2.</p><p>What triangulation does: The math is actually beautiful in its simplicity. If you see the same point from two different camera positions, those two lines of sight have to intersect somewhere in 3D space. Find that intersection, and you’ve got your 3D landmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*49yPHLSN9UXXLf90kJNwgA.png" /></figure><p>Here’s the core algorithm I implemented:</p><pre>TriResult Triangulator::linear(const Eigen::Matrix&lt;double,3,4&gt;&amp; P1,<br>                               const Eigen::Matrix&lt;double,3,4&gt;&amp; P2,<br>                               const Eigen::Vector2d&amp; uv1,<br>                               const Eigen::Vector2d&amp; uv2) const {<br>  // Build the linear system Ax = 0<br>  Eigen::Matrix4d A;<br>  A.row(0) = uv1.x() * P1.row(2) - P1.row(0);  // x1*p13 - p11<br>  A.row(1) = uv1.y() * P1.row(2) - P1.row(1);  // y1*p13 - p12<br>  A.row(2) = uv2.x() * P2.row(2) - P2.row(0);  // x2*p23 - p21<br>  A.row(3) = uv2.y() * P2.row(2) - P2.row(1);  // y2*p23 - p22<br>  <br>  // Solve using SVD - the solution is the null space<br>  Eigen::JacobiSVD&lt;Eigen::Matrix4d&gt; svd(A, Eigen::ComputeFullV);<br>  Eigen::Vector4d Xh = svd.matrixV().col(3);  // rightmost column<br>  <br>  // Convert from homogeneous to 3D coordinates<br>  Eigen::Vector3d X = Xh.head&lt;3&gt;() / Xh[3];<br>  <br>  return X;  // This is our 3D landmark!<br>}</pre><p>The genius here is that we’re solving a linear system. Each camera gives us two equations (one for x-pixel, one for y-pixel), and we need to find the 3D point that satisfies all four equations simultaneously. SVD finds the best solution even when the equations don’t perfectly intersect due to noise.</p><p>The first time I tried it and plotted the results, it felt magical — suddenly I had a 3D point cloud of the scene built just from images.</p><p>But then reality hit: some points were clearly wrong. A few ended up below the ground, others were floating way up in the air. The algorithm will happily triangulate even bad feature matches or noisy measurements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*bAdSNayAY_ADiedq18PiDw.png" /><figcaption>outliers in 3d points are clearly visible</figcaption></figure><p>Here’s what I learned the hard way: every single triangulated point needs quality control. My code became a fortress of validation checks:</p><pre>// Cheirality check: point must be in front of both cameras<br>auto depth1 = (P1 * point_homogeneous)(2);<br>auto depth2 = (P2 * point_homogeneous)(2);<br>if (depth1 &lt;= 0 || depth2 &lt;= 0) return false;  // Behind camera!</pre><pre>// Reprojection error check<br>Vector2d reproj1 = projectToImage(X, P1);<br>Vector2d reproj2 = projectToImage(X, P2);<br>double error1 = (reproj1 - uv1).norm();<br>double error2 = (reproj2 - uv2).norm();<br>if (error1 &gt; 2.0 || error2 &gt; 2.0) return false;  // Too much error!</pre><pre>// Distance sanity check<br>double distance = X.norm();<br>if (distance &lt; 0.1 || distance &gt; 50.0) return false;  // Too close/far!</pre><pre>// Triangulation angle check<br>Vector3d ray1 = (X - camera1_center).normalized();<br>Vector3d ray2 = (X - camera2_center).normalized();<br>double angle = acos(ray1.dot(ray2));<br>if (angle &lt; 2.0 * M_PI/180.0) return false;  // Nearly parallel rays!</pre><p>Second hard lesson: Triangulation is extremely sensitive to noise. A tiny error in feature detection gets amplified into huge errors in 3D position. And if your camera poses aren’t perfectly known? Forget about it.</p><h3>The Scale issue</h3><p>My triangulation module outputs clean, precise-looking 3D coordinates like (-2.34, 0.89, 5.67). But what does that mean? 5.67 what? Meters? Centimeters? And relative to what origin?</p><p>For my very first triangulation, I had to make assumptions. I placed the first camera at the origin with identity rotation, and computed the second camera’s pose using essential matrix decomposition. This gave me a coordinate system, but it was completely arbitrary — the scale was determined by the magnitude of the translation between frames, and the orientation was based on my choice of coordinate axes.</p><p><em>The solution?</em></p><p>Accept the arbitrary coordinate system for internal consistency. Optionally align to real-world scale/orientation later using extra information:</p><ul><li>Stereo baseline</li><li>IMU gravity + scale</li><li>GPS / wheel odometry</li></ul><p>That’s why you’ll often see:</p><blockquote>Monocular VO gives “trajectory up to scale”.</blockquote><p>The math works perfectly fine in this arbitrary coordinate system. What matters is internal consistency — that all your 3D points and camera poses live in the same coordinate frame and relate to each other correctly.</p><h3>A Question to Ponder</h3><p>Now, here’s something I want you to think about before we continue this journey in Part 2:</p><p>If triangulation works so well to create 3D points from two views, why not just keep doing it forever? Why use PnP at all?</p><p>Picture this approach:</p><ul><li>Frame 1–2: Triangulate, get some 3D points</li><li>Frame 2–3: Triangulate again, get more 3D points</li><li>Frame 3–4: Triangulate yet again, get even more 3D points</li><li>And so on…</li></ul><p>Each pair gives you fresh geometry, new 3D structure, a growing collection of landmarks. Seems logical, right? More data, more 3D points, more complete reconstruction.</p><p>So why doesn’t everyone just chain triangulation operations frame after frame? What could possibly go wrong with this beautifully simple approach?</p><p>Take a moment to think about it. Consider what you’ve learned so far about feature matching, geometric noise, and coordinate systems. What problems might emerge if you triangulate between every consecutive pair of frames?</p><h3>Part 1 (Wrap up): Lessons from the Frontend Trenches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*fCDUjos7Ybgt3akBS6GWbA.gif" /><figcaption>the final goal</figcaption></figure><p>As I wrap up this first part , I realize how much I’ve learned just from building these basic components — detection, matching, and triangulation. Each seemed straightforward in isolation, but putting them together revealed the intricate dance of dependencies and failure modes that make SLAM so challenging.</p><p>I started with the innocent goal of “just building the frontend first.” What I got was a masterclass in:</p><ul><li>The fragility of feature matching — where identical features can look different and different features can look identical</li><li>The amplification of noise in triangulation — where tiny pixel errors become massive 3D disasters</li><li>The arbitrariness of coordinate systems — where precise mathematics gives you answers that feel disconnected from reality</li></ul><p>Most importantly, I learned that every component in SLAM is interconnected. You can’t perfect feature detection without considering how matching will work. You can’t optimize triangulation without thinking about downstream pose estimation. Everything affects everything else.</p><h3>What we’ll cover in part 2</h3><p>In Part 2, we’ll dive into what happens when you try to connect these pieces into a complete tracking system. We’ll explore the question I posed above, discover why my naive approaches fell apart, and see how the famous SLAM backend techniques evolved as natural solutions to the problems the frontend creates.</p><p>Spoiler alert: it gets messier before it gets better.</p><p><em>Until then, keep pondering that triangulation question. The answer reveals one of the fundamental insights that separates toy SLAM from real SLAM.</em></p><p><a href="https://github.com/daatsi-aeres/vo-frontend">GitHub - daatsi-aeres/vo-frontend: Self implementation of SLAM frontend. The purpose if self learning and understanding the process.</a></p><p><em>All the code and mini-systems I’ve discussed are available in my repository. I encourage you to run them yourself — there’s no substitute for watching these algorithms succeed and fail with your own data.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecca3532e821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying SVD: The Math Powering Visual SLAM]]></title>
            <link>https://medium.com/@siddharthramasushil/math-that-helps-robots-see-svd-ed2967e5ed59?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed2967e5ed59</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[svd]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 19:30:01 GMT</pubDate>
            <atom:updated>2025-09-03T12:36:04.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*WgaADWsfz2yhReQa.png" /></figure><p>If you’re just starting to learn about computer vision and robotics, you’ve probably encountered the term “SVD” and felt completely overwhelmed. Singular Value Decomposition sounds intimidating, but it’s actually one of the most powerful and practical tools that helps robots understand what they’re seeing. Think of it as a mathematical Swiss Army knife that solves many of the core problems in robot vision.</p><p>Let me walk you through this step by step, and by the end, you’ll understand why SVD is everywhere in robotics and computer vision.</p><h3>What is Singular Value Decomposition?</h3><p>Imagine you have a complex matrix <strong>M</strong> that represents some real-world data — maybe camera images, sensor readings, or geometric relationships. SVD is like having a mathematical X-ray machine that looks inside this matrix and reveals its hidden structure.</p><p><strong>SVD takes any matrix M and breaks it down into three special matrices:</strong></p><p><strong>M = U × D × V^T</strong></p><p>Where:</p><ul><li><strong>U</strong> is an orthogonal matrix (think of it as a rotation matrix)</li><li><strong>D</strong> is a diagonal matrix containing the “singular values”</li><li><strong>V^T</strong> is another orthogonal matrix (also like a rotation matrix)</li></ul><h3>Understanding Singular Values vs Eigenvalues</h3><p>Before we go further, let’s clarify something that confuses many beginners: <strong>What’s the difference between singular values and eigenvalues?</strong></p><p><strong>Eigenvalues</strong> come from eigenvalue decomposition, which only works on square matrices. If you have a square matrix <strong>A</strong>, eigenvalue decomposition finds special vectors (eigenvectors) that don’t change direction when <strong>A</strong> is applied to them — they only get scaled by the eigenvalue.</p><p><strong>Singular values</strong> are more general and work on any matrix (square or rectangular). They measure how much the matrix “stretches” vectors in different directions. The beautiful thing is that singular values are always non-negative real numbers, making them easier to interpret than eigenvalues, which can be complex.</p><p>Think of it this way: if eigenvalue decomposition is like analyzing a perfectly square room, SVD can analyze any room — square, rectangular, or even weirdly shaped.</p><h3>Why Robots Need SVD: The Core Vision Problems</h3><p>Now, let’s explore the specific problems that SVD solves in robotics and computer vision. Each of these connects directly to how robots perceive and navigate their world.</p><h3>1. Solving Homogeneous Equations: Finding Camera Poses</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*GwYUqV_Ed6rmw56z.gif" /></figure><p><strong>The Problem:</strong> When a robot looks at the world through its cameras, it needs to figure out “Where am I?” and “How am I oriented?” This involves solving equations of the form <strong>Ax = 0</strong>, where we want to find a non-trivial solution (not just x = 0).</p><p><strong>Real-world Example:</strong> Imagine your autonomous robot is trying to figure out its position by looking at landmarks. It sees the same building from two different viewpoints and needs to compute the “essential matrix” that describes how it moved between these views.</p><p><strong>How SVD Helps:</strong></p><p>When you have <strong>Ax = 0</strong> and want a non-trivial solution:</p><ol><li>Decompose <strong>A</strong> using SVD: <strong>A = UDV^T</strong></li><li>Look at the smallest singular value in <strong>D</strong> (the bottom-right element)</li><li>If this value is zero (or very close to zero), you have a solution!</li><li>The solution <strong>x</strong> is the last column of <strong>V</strong></li></ol><p><strong>Why this works:</strong> The last column of <strong>V</strong> corresponds to the direction that <strong>A</strong> “crushes” to zero. This gives you the camera motion that’s consistent with your observations.</p><p><strong>Robotics Application:</strong> Every time your robot calculates its pose from visual features, estimates its trajectory, or performs visual SLAM (Simultaneous Localization and Mapping), it’s using this SVD technique.</p><h3>2. Least Squares Problems: Fitting Models to Noisy Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OT6YHlzcduM0vkOg.gif" /></figure><p><strong>The Problem:</strong> Robot sensors are noisy. When your robot tries to fit a line to lidar points, estimate object positions from multiple camera views, or calibrate its sensors, it’s dealing with imperfect data.</p><p><strong>Real-world Example:</strong> Your warehouse robot needs to detect and grasp boxes. Its cameras see the corners of a box, but due to lighting conditions and sensor noise, the measurements aren’t perfect. How do you find the best estimate of the box’s position and orientation?</p><p><strong>How SVD Helps:</strong></p><p>For overdetermined systems (more equations than unknowns), SVD provides the least squares solution:</p><ol><li>If you want to solve <strong>Ax = b</strong> and <strong>A</strong> is not square</li><li>The solution is <strong>x = VD^(-1)U^T b</strong></li><li>This minimizes the error ||Ax — b||²</li></ol><p><strong>Robotics Application:</strong></p><ul><li><strong>3D reconstruction:</strong> Building 3D models from multiple camera views</li><li><strong>Sensor fusion:</strong> Combining data from cameras, lidar, and IMUs</li><li><strong>Object pose estimation:</strong> Determining how objects are oriented in space</li><li><strong>Robot calibration:</strong> Fine-tuning camera parameters and robot kinematics</li></ul><h3>3. Computing the Null Space: Understanding Constraints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*bvSNKWWxohg9JTww.gif" /></figure><p><strong>The Problem:</strong> Sometimes robots need to understand what movements or actions are “forbidden” or “impossible” given the current constraints.</p><p><strong>Real-world Example:</strong> Your humanoid robot is trying to reach for an object while keeping its balance. Certain joint movements might cause it to fall over. The null space represents the set of joint motions that don’t affect the robot’s hand position — these are the “safe” movements.</p><p><strong>How SVD Helps:</strong></p><p>The null space of <strong>A</strong> consists of all vectors <strong>x</strong> such that <strong>Ax = 0</strong>:</p><ol><li>Compute SVD: <strong>A = UDV^T</strong></li><li>Find columns in <strong>V</strong> corresponding to zero singular values</li><li>These columns span the null space</li></ol><p><strong>Robotics Applications:</strong></p><ul><li><strong>Redundant robot control:</strong> When a robot arm has more joints than needed for a task</li><li><strong>Motion planning:</strong> Finding valid paths that satisfy multiple constraints</li><li><strong>Force control:</strong> Determining directions where the robot can move without applying force</li></ul><h3>4. Pseudo-inverse: Dealing with Unsolvable Problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X2JFgYTgYhJ10Uub.jpg" /><figcaption>multiple sensor, same info, both incorrect to some degree</figcaption></figure><p><strong>The Problem:</strong> In the real world, many problems don’t have exact solutions. Your robot might have more sensor readings than unknowns, or the system might be inconsistent due to noise.</p><p><strong>Real-world Example:</strong> Your delivery drone is using GPS, compass, accelerometer, and visual odometry to determine its position. These sensors give conflicting information due to GPS errors, magnetic interference, and visual tracking drift. What’s the “best” estimate of where the drone actually is?</p><p><strong>How SVD Helps:</strong></p><p>The pseudo-inverse <strong>A^+</strong> gives you the “best possible” solution:</p><ol><li><strong>A^+ = VD^+U^T</strong></li><li><strong>D^+</strong> is <strong>D</strong> with non-zero elements inverted and transposed</li><li>For <strong>Ax = b</strong>, the solution <strong>x = A^+b</strong> minimizes ||x|| subject to minimizing ||Ax — b||</li></ol><p><strong>Robotics Applications:</strong></p><ul><li><strong>Sensor fusion:</strong> Optimally combining inconsistent sensor data</li><li><strong>Over-actuated systems:</strong> Controlling robots with more actuators than degrees of freedom</li><li><strong>Inverse kinematics:</strong> Finding joint angles for desired end-effector positions</li></ul><h3>5. Matrix Approximation: Reducing Complexity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*pm5OAdUyA-nY1rZ_.gif" /></figure><p><strong>The Problem:</strong> Robot vision systems often deal with massive amounts of data. Processing high-resolution images or large point clouds in real-time requires smart approximations.</p><p><strong>Real-world Example:</strong> Your robot vacuum is building a map of your house using its camera. Each room scan generates thousands of feature points. To run in real-time, it needs to compress this data while keeping the essential structure.</p><p><strong>How SVD Helps:</strong></p><p>Low-rank approximation keeps only the most important information:</p><ol><li>Compute <strong>A = UDV^T</strong></li><li>Keep only the largest <strong>k</strong> singular values</li><li>Set smaller singular values to zero</li><li>Reconstruct: <strong>A_approx = U_k D_k V_k^T</strong></li></ol><p><strong>Robotics Applications:</strong></p><ul><li><strong>Image compression:</strong> Reducing data for transmission and storage</li><li><strong>Feature reduction:</strong> Keeping only the most important visual features</li><li><strong>Map compression:</strong> Storing efficient representations of large environments</li><li><strong>Real-time processing:</strong> Reducing computational load for faster response</li></ul><h3>6. Enforcing Rank Deficiency: Geometric Constraints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YS6PH4uDZBjvZ_Ll.png" /></figure><p><strong>The Problem:</strong> In computer vision, certain matrices must satisfy specific mathematical properties. For example, the fundamental matrix (which relates points between two camera views) must have rank 2, not rank 3.</p><p>(read: <a href="https://www.baeldung.com/cs/fundamental-matrix-vs-essential-matrix">https://www.baeldung.com/cs/fundamental-matrix-vs-essential-matrix</a>)</p><p><strong>Real-world Example:</strong> Your autonomous car is trying to match features between its left and right cameras for stereo vision. The mathematical relationship between these cameras is described by the fundamental matrix, which must be rank-deficient to be geometrically valid.</p><p><strong>How SVD Helps:</strong></p><p>To enforce rank deficiency:</p><ol><li>Compute the initial matrix estimate</li><li>Apply SVD: <strong>F = UDV^T</strong></li><li>Set the smallest singular value in <strong>D</strong> to zero</li><li>Reconstruct: <strong>F_corrected = UD_corrected V^T</strong></li></ol><p><strong>Robotics Applications:</strong></p><ul><li><strong>Stereo vision:</strong> Ensuring geometric consistency between camera pairs</li><li><strong>Visual SLAM:</strong> Maintaining mathematical correctness in mapping</li><li><strong>3D reconstruction:</strong> Enforcing geometric constraints in multi-view systems</li><li><strong>Camera calibration:</strong> Ensuring estimated parameters are geometrically valid</li></ul><h3>The Computational Reality: Why SVD is Worth the Cost</h3><p>I won’t lie to you — SVD is computationally expensive. For an <strong>m×n</strong> matrix, it takes <strong>O(min(m,n)³)</strong> operations. For large matrices, this can be slow.</p><p>But here’s why robots still use it everywhere:</p><ol><li><strong>Numerical stability:</strong> SVD is incredibly robust to noise and numerical errors</li><li><strong>Generality:</strong> It works on any matrix, square or rectangular</li><li><strong>Rich information:</strong> You get insights into matrix rank, null space, and condition number</li><li><strong>Proven reliability:</strong> Decades of use in critical applications</li></ol><p>Modern robotics systems often use approximations or specialized hardware to make SVD faster, but the fundamental technique remains invaluable.</p><h3>Putting It All Together: SVD in Robot Vision Systems</h3><p>Let me paint you a picture of how all these pieces work together in a real robot:</p><p>Imagine your autonomous robot exploring an unknown building. Here’s how SVD helps at every step:</p><ol><li><strong>Camera calibration</strong> (matrix approximation): SVD helps estimate precise camera parameters</li><li><strong>Feature matching</strong> (homogeneous equations): Finding corresponding points between images</li><li><strong>Pose estimation</strong> (least squares): Determining robot position from visual landmarks</li><li><strong>3D reconstruction</strong> (pseudo-inverse): Building 3D maps from multiple viewpoints</li><li><strong>Constraint satisfaction</strong> (null space): Planning motions that maintain geometric consistency</li><li><strong>Real-time operation</strong> (rank deficiency): Ensuring mathematical correctness while meeting speed requirements</li></ol><p>Every one of these steps relies on SVD’s ability to reveal the hidden structure in matrices and provide robust solutions to challenging mathematical problems.</p><h3>Your Journey with SVD</h3><p>If you’re feeling overwhelmed, remember that understanding SVD is like learning to drive. At first, you think about every small detail — checking mirrors, adjusting seat position, understanding each control. But eventually, it becomes intuitive, and you focus on where you want to go rather than the mechanics of getting there.</p><p>Start by implementing simple examples. Try using SVD to solve a small homogeneous system. Experiment with image compression using low-rank approximation. Each small success will build your intuition about when and why to use this powerful tool.</p><p>The mathematics might seem abstract now, but remember: every time a robot successfully navigates a room, recognizes an object, or builds a map of its environment, SVD is working behind the scenes, turning noisy sensor data into reliable understanding of the world.</p><p>That’s the real beauty of SVD —it’s not just mathematical theory. It’s the foundation that helps robots see, understand, and interact with the world around them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed2967e5ed59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foundations of Robot Perception: A Beginner’s Guide to the Math]]></title>
            <link>https://medium.com/@siddharthramasushil/the-math-that-makes-robots-see-a-fellow-beginners-guide-to-computer-vision-math-pa-6f9a870fddec?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f9a870fddec</guid>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 21:13:57 GMT</pubDate>
            <atom:updated>2025-09-03T12:34:49.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*gZuhO6PQ0fxGL9myfPMrFw.png" /></figure><p>So you’re getting into robotics and computer vision, and suddenly everyone’s throwing around terms like “singular value decomposition” and “homogeneous coordinates” like they’re ordering coffee. I totally get it — I’ve been there, staring at equations that look like someone sneezed algebra all over my screen.</p><p>After banging my head against these concepts for way too long, I figured I’d write down what I wish someone had told me when I started. This isn’t going to be some formal textbook explanation — think of it more like notes from a fellow traveler who’s still figuring things out but has stumbled through enough math to share the shortcuts.</p><h3>The Big Picture: Why This Math Even Matters</h3><p>Before we dive into the scary equations, let’s talk about why we need this stuff. When you’re building a robot that needs to see the world, you’re basically asking it to solve puzzles like:</p><ul><li>“Where is that object in 3D space based on what I see in this 2D camera image?”</li><li>“How did the robot move between these two camera shots?”</li><li>“Which points in these two images are actually the same real-world point?”</li></ul><p>All of these problems boil down to solving systems of equations. And unfortunately, the real world is messy — your measurements have noise, you might have more equations than unknowns, or sometimes the math just doesn’t work out perfectly. That’s where all this linear algebra comes to the rescue.</p><h3>Linear Systems: The Foundation of Everything</h3><h3>The Simple Case (When Life is Good)</h3><p>Let’s start with the basics: Ax = b. This just means you have some matrix A, an unknown vector x, and a known result b. You’re trying to figure out what x should be.</p><p>In the perfect world, A is a nice square matrix with full rank, and boom — you get one clean solution. It’s like having exactly the right number of clues to solve a puzzle.</p><pre>Example: You know your robot moved some distance in x and y directions, <br>and you have exactly two sensor readings. Perfect!</pre><h3>When You Have Too Much Information (Overdetermined Systems)</h3><p>Here’s where things get real. In actual robotics, you almost always have more measurements than unknowns. Your robot might have 50 different sensor readings trying to tell you about 6 movement parameters.</p><p>The problem? Those sensors are noisy. So instead of having a perfect <br>Ax = b, you end up with a system that has no exact solution because your measurements don’t agree perfectly.</p><p>Enter least squares — instead of solving Ax = b exactly, you minimize<br> ||Ax — b||². You’re basically saying “I can’t make everyone happy, but let me find the solution that makes everyone as least unhappy as possible.”</p><p>The magic formula becomes: x = (A^T A)^(-1) A^T b</p><p>Don’t memorize this — just know that least squares is your friend when you have noisy, redundant measurements (which is always).</p><h3>Some complicated terms to clarify:</h3><p>Before we dive into this Ax = 0 business, let me explain a couple of concepts:</p><p>Matrix rank is basically asking: “How many truly independent pieces of information does this matrix contain?” Think of it like this — if you have a 3×3 matrix, it <em>could</em> contain 3 independent pieces of information (full rank), but maybe some of its rows are just copies or combinations of other rows.</p><p>Here’s a simple example:</p><pre>Matrix: [1  2  3]<br>        [2  4  6]  ← This row is just 2× the first row<br>        [4  5  6]</pre><p>Even though this is a 3×3 matrix, it only has a rank of 2 because the second row isn’t giving us any new information — it’s just the first row doubled. The matrix is “rank deficient.”</p><p>What does “squashing” mean? When I say a matrix “squashes” a vector, I mean it transforms that vector in a way that reduces its dimensionality or makes it smaller. Think of it like stepping on a balloon — you’re taking something that exists in 3D space and flattening it down.</p><p>If a matrix has full rank, it generally preserves the “size” of the space you’re working in. But if it’s rank deficient, it squashes vectors down into a smaller dimensional space. In the extreme case, it can squash certain vectors all the way down to zero!</p><p>Non-trivial solutions: This just means “solutions that aren’t boring.” The trivial solution to Ax = 0 is always x = 0 (the zero vector). That’s like saying “well, if I multiply anything by zero, I get zero” — technically correct but not very useful.</p><p>We’re looking for non-zero vectors that still make Ax = 0. These are the interesting cases that actually tell us something meaningful about our system.</p><h3>The Mysterious Case: Ax = 0 (Homogeneous Systems)</h3><p>This one confused me for ages. Why would you want Ax to equal zero? Isn’t that just x = 0?</p><p>Well, here’s the thing — we’re usually looking for non-trivial solutions (solutions that aren’t just the zero vector). This pops up everywhere in computer vision:</p><ul><li>Finding camera parameters</li><li>Computing relationships between camera views</li><li>Determining fundamental matrices</li></ul><p>The key insight: if your matrix A doesn’t have full rank (it’s “rank deficient”), then there are vectors that A can squash down to zero. These vectors live in something called the null space of A.</p><h3>SVD: Your Swiss Army Knife</h3><p>Singular Value Decomposition sounds terrifying, but it’s actually your best friend for solving these homogeneous systems.</p><p>Think of SVD as taking any matrix A and breaking it into three pieces:</p><p>A = U D V^T</p><ul><li>U and V are rotation-like matrices</li><li>D is a diagonal matrix with singular values (think of them as “importance scores”)</li></ul><p>Here’s the practical part: if you want to solve Ax = 0, you:</p><ol><li>Compute the SVD of A</li><li>Look at the smallest singular value in D</li><li>If it’s zero (or very close to zero), the corresponding column in V is your solution!</li></ol><p>It’s like having a detector that finds the “weakest direction” in your system — exactly what you need for those tricky homogeneous problems.</p><h3><strong><em>A geometric picture</em></strong></h3><p>Imagine the unit sphere. Multiplying by A stretches and rotates that sphere into a “hyper-ellipse.”</p><ul><li>Columns of V point along the original axes.</li><li>Singular values in Σ scale those axes (long axis = big singular value).</li><li>Columns of U show where the stretched axes end up.<br>So SVD tells you exactly <em>how</em> and <em>where</em> your data is being stretched.</li></ul><p>Why robotics / vision people care</p><ol><li>Solving Ax = 0 (homogeneous problems)</li></ol><ul><li>Compute SVD of A.</li><li>The right-singular vector whose singular value is <em>zero</em> (or smallest) lives in the null-space and pops out as your non-trivial solution.</li></ul><ol><li>Diagnosing rank — count the non-zero singular values; that number <em>is</em> the rank.</li><li>Pseudo-inverse — need a stable inverse for a skinny or fat matrix? Flip Σ’s non-zero entries and do V Σ⁻¹ Uᵀ.</li><li>Least-squares with dignity — SVD gives the numerically safest least-squares answer, especially when A is close to rank-deficient.</li><li>Real-world goodies</li></ol><ul><li><strong>Image compression </strong>— keep only the largest k singular values, throw the rest away, and you still have a recognisable picture but with far fewer bytes.</li><li><strong>Noise filtering / denoising</strong> — small singular values often capture noise, so discarding them cleans the signal.</li><li><strong>Feature reduction</strong> — retaining the top singular values is a dead-simple form of PCA for datasets or word embeddings.</li><li><strong>Eight-point algorithm &amp; essential matrices </strong>— computer-vision classics boil down to “compute SVD, pick the null-space vector, reshape into a matrix,” then you’re done.</li></ul><h3>Skew-Symmetric Matrices: The Cross Product’s Cooler Cousin</h3><p>This one’s actually pretty neat once you see the trick. You know how cross products work in 3D? a × b gives you a vector perpendicular to both a and b.</p><p>Well, it turns out you can write that cross product as a matrix multiplication: [a]× b, where [a]× is a skew-symmetric matrix built from vector a.</p><p>Why is this useful? Because sometimes it’s easier to work with matrices than cross products, especially when you’re chaining operations together or taking derivatives.</p><p>The pattern is simple:</p><pre>If a = [a1, a2, a3], then [a]× = [ 0  -a3   a2]<br>                                 [ a3   0  -a1]<br>                                 [-a2  a1   0 ]</pre><p>This shows up constantly when you’re working with rotations and 3D geometry.</p><h3>Rotation Matrices and Their Quirks</h3><p>Rotation matrices are special — they preserve lengths and angles. This means R R^T = I (the matrix times its transpose equals identity).</p><p>Here’s something cool: if you take the derivative of a rotation matrix, you get something related to skew-symmetric matrices. This becomes super useful when you’re trying to optimize problems involving rotations.</p><p>For small rotations, you can approximate a rotation matrix as I + [ω]×, where ω is a small rotation vector and [ω]× is that skew-symmetric matrix we talked about.</p><h3>Practical Tips from the Trenches</h3><ol><li>Don’t implement SVD yourself — use a good linear algebra library (NumPy, Eigen, etc.). They’re optimized and handle edge cases you haven’t thought of.</li><li>When solving Ax = 0, always check the singular values — if the smallest one isn’t close to zero, you might not have a good solution.</li><li>Least squares is everywhere — camera calibration, pose estimation, structure from motion. Once you recognize the pattern, half the battle is won.</li><li>Visualization helps — try to understand what your matrices are doing geometrically, not just algebraically.</li><li>Start with 2D examples — work through simple cases by hand before jumping into full 3D problems.</li></ol><h3>The Reality Check</h3><p>Look, I’m not going to lie — this math can be frustrating. There are days when you’ll stare at equations and wonder if you’re cut out for this. I’ve been there.</p><p>But here’s the thing: you don’t need to derive everything from first principles. You need to understand what tools are available, when to use them, and how to implement them. The deep theoretical understanding can come later (or never — that’s okay too!).</p><p>The most important skill is recognizing patterns: “Oh, this looks like a least squares problem” or “This feels like I need to find a null space.” Once you build that intuition, the specific techniques become tools in your toolbox rather than mysterious incantations.</p><h3>Moving Forward</h3><p>This barely scratches the surface — we haven’t even talked about homogeneous coordinates, epipolar geometry, or bundle adjustment. But hopefully, this gives you a foundation to build on.</p><p>The key is to keep connecting the math back to the actual problems you’re trying to solve. Every time you see an equation, ask yourself: “What is this actually doing? What problem is it solving?”</p><p>And remember — everyone struggles with this stuff initially. The people who seem to get it effortlessly? They’ve just had more practice being confused and working through it.</p><p>Keep building, keep learning, and don’t let the math scare you away from doing cool robotics stuff. You’ve got this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f9a870fddec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Epipolar Geometry in Practice: Build, Visualize, Understand]]></title>
            <link>https://medium.com/@siddharthramasushil/epipolar-geometry-in-practice-build-visualize-understand-384959ecf69c?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/384959ecf69c</guid>
            <category><![CDATA[slam]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[perception]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 20:54:19 GMT</pubDate>
            <atom:updated>2025-08-22T20:55:04.744Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been neck-deep in SLAM lately, and epipolar geometry finally “clicked” for me when I forced myself to build it end-to-end. This post is my plain-English write-up of the flow: from feeding two images into a pipeline, to drawing epipolar lines that reveal how the cameras moved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-MzxjwnU5BzKhxdoenxwfA.gif" /></figure><p>I built a tiny C++/OpenCV repo you can run locally to <em>feel</em> epipolar geometry instead of just reading about it.</p><p><em>(</em><a href="https://github.com/daatsi-aeres/epipolar-visualizer"><em>https://github.com/daatsi-aeres/epipolar-visualizer</em></a><em>)</em></p><p>It’s a fast way to build intuition for what each stage is doing: how detection density affects matching, how ratio test vs. cross-check shapes outliers, how the RANSAC threshold trades clean geometry for coverage, and where the epipoles land when the camera mostly translates vs. rotates.</p><h3>The big picture (why epipolar geometry matters)</h3><p>Given two images of the same scene, each 3D point projects to a pixel in the left image and a pixel in the right image. Epipolar geometry tells me <strong>how those two pixels are constrained</strong>, purely from camera motion and intrinsics — <strong>no depth</strong> required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*AsO2uY0P-1sNDmMZWIx2ZA.png" /></figure><p>The constraint is the famous epipolar equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*pMGj6yEOBQBlddLBMUq9Eg.png" /></figure><ul><li>F is the <strong>fundamental matrix</strong> (uncalibrated).</li><li>If I know intrinsics K, I work in normalized coordinates and use the <strong>essential matrix</strong> E instead:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*9IcFaO8SY1r53HWVGT_HIg.png" /></figure><p><strong>What I get:</strong> lines (epipolar lines) and motion up to scale (rotation RRR, translation direction ttt).<br> <strong>What I don’t get:</strong> exact 3D coordinates, because I don’t know depth from a single stereo pair alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*IPRDvgYjAEgFEaPDuvaGHQ.png" /></figure><h3>The practical flow: from two images to epipolar lines</h3><p>Here’s the exact sequence I implemented in C++/OpenCV.</p><h3>1) Load and pre-process the images</h3><p><strong>Goal:</strong> get two clean frames that are geometrically comparable.</p><ul><li><strong>Undistortion (recommended if you know intrinsics/distortion):</strong><br> Radial/tangential distortion bends straight epipolar lines. If you have camera intrinsics (fx,fy,cx,cy)(fx, fy, cx, cy)(fx,fy,cx,cy) and distortion coeffs, undistort both images first (cv::undistort).</li><li><em>Why it matters:</em> F and E assume ideal pinhole projections; distortion inflates residuals and hurts inlier counts.</li><li><strong>Grayscale conversion:</strong><br> Most detectors/descriptors operate on grayscale (cv::cvtColor(..., COLOR_BGR2GRAY)).</li></ul><h3>2) Detect + describe features (ORB in practice)</h3><p><strong>What ORB gives you:</strong> keypoints (pixel locations + scale/orientation) and <strong>binary descriptors</strong> (CV_8U).</p><p>Key <strong>parameters</strong> you’ll set in cv::ORB::create(...) and what they do:</p><ul><li>nfeatures (e.g., 500–3000):<br> Target number of retained keypoints across the scale pyramid.<br> <em>Trade-off:</em> more features → better coverage + more matches → more compute later.</li><li>scaleFactor (e.g., 1.2–1.4) and nlevels (e.g., 6–12):<br> Define the image pyramid for scale invariance.<br> <em>Intuition:</em> smaller scaleFactor and larger nlevels cover scale more finely (robust on zoom), but cost more.</li><li>fastThreshold (FAST corner threshold, e.g., 10–30):<br> Lower → more sensitive (more points, noisier). Higher → fewer, stronger corners.</li><li>edgeThreshold, patchSize (usually leave defaults 31/31):<br> Affect how close to borders keypoints are accepted and BRIEF patch size.</li><li>WTA_K (2 or 4) and scoreType (HARRIS_SCORE vs FAST_SCORE):<br> Advanced knobs. WTA_K=4 can improve descriptor distinctiveness at small extra cost.</li></ul><p><strong>Numerical stability tip:</strong> if you plan to estimate E, make sure your intrinsics are roughly right — scale errors in fx,fyfx,fyfx,fy change normalized coordinates and can destabilize the solver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAkh92CsbGDB9ngJv3lcPw.png" /></figure><h3>3) Match descriptors (left ↔ right)</h3><p><strong>Outputs:</strong> tentative correspondences. This stage creates inliers (good matches) <em>and</em> outliers (bad matches); the next stage filters them.</p><p>Two common <strong>matchers</strong> for ORB:</p><p><strong>BFMatcher (Hamming metric)(normally this is preferred for ORB):</strong></p><ul><li>cv::BFMatcher(cv::NORM_HAMMING, crossCheck).</li><li>crossCheck=true: keeps only <strong>mutual 1-NN</strong> matches (cleaner, fewer).</li><li>crossCheck=false: enables <strong>KNN (k=2) + Lowe ratio</strong>.</li></ul><p><strong>FLANN (approximate NN):</strong><br>For ORB you must either convert to CV_32F and use L2, or configure an LSH index. Quality can be fine, but BF/Hamming is the canonical baseline for binary descriptors.</p><p><strong>Filtering parameters</strong> you’ll actually tune:</p><ul><li><strong>Ratio test</strong> (Lowe): choose a threshold ~<strong>0.7–0.85</strong>.<br> For each descriptor, look at its two nearest neighbours (d1≤d2). <br> Accept if d1&lt;ρd2​.<br> <em>Effect:</em> rejects ambiguous matches (repetitive textures, edges).<br>We only allow clean matches to go ahead, any point whose best and 2nd best match are same means it is NOT a unique point.</li><li><strong>Cross-check</strong>: boolean.<br>Only allows matches when best match of left to right is also best batch from right to left descriptors.<br>When on, you <strong>don’t</strong> use the ratio test (they’re mutually exclusive in BF).<br> <em>Effect:</em> higher precision, lower recall; great when you have plenty of keypoints.</li><li><strong>Distance cap</strong> (optional):<br> With ORB/Hamming, you can discard matches with distance &gt; T (e.g., 50–80) to cull weak similarities before RANSAC.</li></ul><p><strong>Good practice:</strong> do <em>either</em> ratio test <em>or</em> cross-check, not both (BF doesn’t support KNN with crossCheck=true).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qI0wQYoEQXleSGlgwlqeNw.png" /></figure><h3>4) Robust model estimation with RANSAC</h3><p><strong>Goal:</strong> estimate a clean F (uncalibrated) or E (calibrated) despite outliers.</p><h3>4.1 Choose the model</h3><ul><li><strong>Fundamental matrix F</strong> (pixel coordinates):<br> Use when you don’t trust intrinsic; works on distorted images but better after undistort or normalization.</li><li><strong>Essential matrix E</strong> (normalized coordinates):<br> Use when you have intrinsics (K). Lets you recover (R,t) up to scale.</li></ul><h3>4.2 Minimal solvers inside RANSAC</h3><ul><li><strong>8-point (or 7-point) for F:</strong> linear SVD solve on normalized points, then <strong>enforce rank-2</strong> by zeroing the smallest singular value.<br>(if you want you can go in depth with the 8-point method and understand the maths behind it, I will not go into the detail in this article)</li><li><strong>5-point for E:</strong> polynomial solver that enforces essential constraints (σ1=σ2, σ3=0).</li></ul><h3>4.3 The residual (how we score a model)</h3><ul><li><strong>Sampson distance</strong> (fast, robust approximation of geometric error).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*-x67dUtR-2ZrexB428MtdQ.png" /></figure><ul><li>After we get a solution from the above method it is tested on ALL pixel matches and an error score is calculated, if the error is beyond the threshold set by us, the point becomes an outlier. The process is repeated for several cycles, we take different subset of points each time.</li><li><strong>Inlier threshold (pixels)</strong> — <em>the most impactful parameter here</em>:<br> Typical values: <strong>0.5–2.0 px</strong> for undistorted, high-res images; up to <strong>3–4 px</strong> for noisier data.<br> <em>Effect:</em> lower = stricter (fewer, cleaner inliers); <br> higher = more inliers but risk of accepting wrong geometry.</li></ul><h3>4.4 RANSAC control parameters</h3><ul><li><strong>Confidence</strong> (e.g., 0.99–0.999):<br> Probability that at least one all-inlier sample is tested; higher → more iterations → slower but safer.</li><li><strong>Max iterations</strong> (optional hard cap):<br> Prevents worst-case runtime when the inlier ratio is very low or the scene is degenerate.</li><li><strong>Probability / MAGSAC / LMedS</strong> (alternatives):<br> OpenCV also offers LMedS; newer libraries offer MAGSAC++. They change how inliers are counted but keep the same big picture.</li></ul><h3>4.5 Refit (“polish”) on all inliers</h3><ul><li>In the end we Re-estimate the F(or E) with <strong>all inliers</strong> (not just the minimal subset).</li></ul><h3>5) If using E: recover pose (R,t)</h3><ul><li><strong>Decomposition:</strong> SVD of E yields <strong>four</strong> (R,t) candidates.</li><li><strong>Cheirality check:</strong> Triangulate a small set of inliers for each candidate; pick the one where the majority land <strong>in front</strong> of both cameras.</li><li><strong>Scale ambiguity:</strong> only the <strong>direction</strong> of t is known with a single stereo pair.</li></ul><h3>6) Compute and draw epipolar lines</h3><p>With the final F in <strong>pixel coordinates</strong> (if you estimated E, convert via <br>F=K<em>−⊤ </em>EK−1):</p><ul><li><strong>Right-image lines from left points:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*AQoTaodwHzA6M5GS97-3Xw.png" /></figure><ul><li><strong>Left-image lines from right points:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*X-cxlh_mqjMU9Rl0vV8uAQ.png" /></figure><p>For each line ℓ=(a,b,c)⊤:</p><ul><li>Clip the line segment to the image rectangle and draw it (thin lines help reduce clutter).</li><li>You’ll often draw <strong>lines for inliers only</strong> so the plot isn’t noisy.</li></ul><p><strong>Epipoles (where the lines converge):</strong></p><ul><li><strong>Left epipole</strong> e1​ satisfies F*e1=0 (nullspace of F).</li><li><strong>Right epipole</strong> e2 satisfies F⊤*e2=0.</li><li>In rectified stereo, epipoles move to infinity → epipolar lines are parallel (typically horizontal).</li></ul><p><strong>Interpreting the pattern:</strong></p><ul><li>Radiating lines toward a point near the image center: <br>motion has a strong forward/backward component.</li><li>Nearly parallel lines: <br>mostly sideways translation with small rotation (classic stereo rig).</li><li>Lines pivoting around a point far off to a side: <br>significant rotation about an axis.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVhPEAdBSFGitzivAzKynQ.png" /></figure><h3>What this geometry gives you — and what it never will (by itself)</h3><p><strong>Gives:</strong></p><ul><li>The <strong>family of lines</strong> where the mate of each point must lie (hard geometric constraints).</li><li><strong>Relative rotation RRR</strong> and <strong>translation direction ttt</strong> (if using E), i.e., motion <strong>up to scale</strong>.</li><li>A principled way to <strong>filter matches</strong> (inliers) for later stages (triangulation, PnP, bundle adjustment).</li></ul><p><strong>Does not give:</strong></p><ul><li><strong>Metric depth</strong> (and therefore not exact 3D point coordinates) from a single pair alone — scale is missing.</li><li>The absolute magnitude of translation (you need stereo baseline scale, IMU, known object size, or multi-view with loop/sensor constraints).</li></ul><h3>My intuition in one paragraph</h3><p>RANSAC is a reality check. Matches propose a candidate F(or E), the model proposes a family of lines, and <strong>every correspondence must lie close to its line</strong> to be counted. The winning model is simply the one that <strong>explains the most points within a pixel tolerance</strong>. Then I refit on just those agreeing points. That’s why good <strong>match filtering</strong> (ratio or cross-check) and a sensible <strong>pixel threshold</strong> make everything feel stable.</p><h3>The mini project I built.</h3><p>If this clicked for you and you want to <em>feel</em> the geometry yourself, grab the code from my <a href="https://github.com/daatsi-aeres/epipolar-visualizer">GitHub repo</a>, load any stereo-ish pair, and play. If you think of a cool feature — “inliers-only” match view, rectification demo, homography vs. fundamental auto-selection, result export, you name it — please open an issue or a PR. I’d love to build this into the go-to sandbox for learning epipolar geometry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=384959ecf69c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Rotation Mathematics for SLAM]]></title>
            <link>https://medium.com/@siddharthramasushil/understanding-rotation-mathematics-for-slam-13128f8699dd?source=rss-fbf100db3739------2</link>
            <guid isPermaLink="false">https://medium.com/p/13128f8699dd</guid>
            <dc:creator><![CDATA[Siddharth Rama Sushil]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 12:28:20 GMT</pubDate>
            <atom:updated>2025-08-08T12:39:34.215Z</atom:updated>
            <content:encoded><![CDATA[<p>SLAM (<strong>Simultaneous Localization and Mapping</strong>) is at the heart of robotics and computer vision.<br>Whether you’re fusing sensor data, visualizing a camera’s path, or optimizing a pose graph, you’re always manipulating <strong>rotations</strong> and <strong>poses</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*EwO0wh-DBUY1XcNG.png" /></figure><p>This guide will take you from rotating a single vector in space, step by step, all the way to handling full 3D poses — complete with rotations, translations, and the skills to switch between different rotation representations like a pro.</p><h3>Step 1 — Rotation Matrices</h3><h3>Concept</h3><p>Think of a rotation matrix as a precise mathematical tool for spinning things around in 3D space without changing their shape or size. If you imagine holding a stick in the air and turning it, a rotation matrix is the exact set of numbers that tells you where every point on that stick ends up after the turn. What makes it special is that it doesn’t stretch, shrink, or bend anything — it’s like hitting “rotate” in a 3D modeling program with the “keep proportions” box always checked. In our case, a <strong>3×3</strong> rotation matrix handles the job in a perfectly predictable way: you give it a vector (your starting direction), and it returns the vector’s new coordinates after rotation. The key magic is that the matrix preserves distances and angles, meaning your shapes stay rigid while moving. This property is why rotation matrices are everywhere in robotics, computer vision, and especially SLAM — they’re the clean, reliable way to shift perspectives between different coordinate frames without distorting the world.</p><h3>The math</h3><p>For a rotation about the Z-axis by θ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*d3MeVDeTSSkjL46Io3hYKw.png" /></figure><h3>Why it matters for SLAM</h3><ul><li>Used to transform points between coordinate frames.</li><li>Easy to compose: Rac=Rab*Rbc</li></ul><h3>C++ example</h3><pre>#include &lt;Eigen/Core&gt;<br>#include &lt;cmath&gt;<br>#include &lt;iostream&gt;<br>using namespace Eigen;<br>using namespace std;<br><br>int main() {<br>    double th = M_PI/4; // 45 degrees<br>    Matrix3d R;<br>    R &lt;&lt; cos(th), -sin(th), 0,<br>         sin(th),  cos(th), 0,<br>         0,        0,       1;<br><br>    Vector3d v(1,0,0);<br>    Vector3d vp = R * v;<br><br>    cout &lt;&lt; &quot;Rz(45°):\n&quot; &lt;&lt; R &lt;&lt; &quot;\n&quot;;<br>    cout &lt;&lt; &quot;v&#39; = &quot; &lt;&lt; vp.transpose() &lt;&lt; &quot;\n&quot;; // ~[0.707 0.707 0]<br>}</pre><h3>Exercises</h3><ol><li>Change θ to 90° and predict v′ before running.</li><li>Rotate (0,1,0)(0,1,0) by 45° and check results.</li><li>Verify ∥v′∥=∥v∥</li></ol><h3>Step 2 — Axis–Angle &amp; Rodrigues’ Formula</h3><h3>Concept</h3><p>Another powerful way to describe a rotation is with an <strong>axis–angle</strong> pair. Imagine you have a thin, perfectly rigid rod floating in space — that rod will be your <strong>axis of rotation</strong>. It’s defined by a unit vector <strong>u</strong> (meaning it has length 1) that points in the direction of the axis. Then, all you need is a single number, the angle <strong>θ</strong>, which tells you how far to spin around that axis. Together, <strong>u</strong> and <strong>θ</strong> fully describe any 3D rotation. This is incredibly intuitive — it’s basically the same way you’d describe turning a screwdriver (“rotate 90° around this shaft”). The beauty of the axis–angle representation is that it works for <em>any</em> orientation, not just nice, tidy cases like “about the X-axis” or “about the Z-axis.”</p><p>When we want to convert this idea into a rotation matrix, we can use <strong>Rodrigues’ formula</strong> — a neat mathematical shortcut that turns “rotate by θ around u” into a clean 3×3 matrix. In robotics and SLAM, this is especially useful because it lets us store and interpolate rotations compactly, then expand them into full matrices whenever we need to apply them to points or coordinate frames.</p><h3>The math</h3><p><strong>Rodrigues’ formula</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*BNbF-pz0rC2JKJC1MysbLw.png" /></figure><h3>Why it matters for SLAM</h3><ul><li>Compact storage (rotation vector ω=θu).</li><li>Core to Lie algebra updates in optimization.</li><li>Easy to convert to a matrix for application.</li></ul><h3>C++ example</h3><pre>#include &lt;Eigen/Core&gt;<br>#include &lt;Eigen/Geometry&gt;<br>#include &lt;iostream&gt;<br>#include &lt;cmath&gt;<br>using namespace Eigen;<br>using namespace std;<br><br>int main() {<br>    Vector3d axis(1, 1, 0);<br>    axis.normalize();<br>    double theta = M_PI / 4;<br><br>    AngleAxisd rot(theta, axis);<br>    Vector3d v(1, 0, 0);<br>    Vector3d v_rotated = rot * v;<br><br>    cout &lt;&lt; &quot;Axis: &quot; &lt;&lt; axis.transpose() &lt;&lt; &quot;\n&quot;;<br>    cout &lt;&lt; &quot;Rotation matrix:\n&quot; &lt;&lt; rot.matrix() &lt;&lt; &quot;\n&quot;;<br>    cout &lt;&lt; &quot;Rotated vector: &quot; &lt;&lt; v_rotated.transpose() &lt;&lt; &quot;\n&quot;;<br>}</pre><ol><li>Use u=(0,0,1) and check it matches Step 1.</li><li>Try u=(0,1,0)and rotate (1,0,0).</li><li>Try u=(1,1,1) θ=120, see if coordinates cycle.</li></ol><h3>Math to internalize</h3><ul><li>Rotation vector ω → θ=∥ω∥, u = ω / θ.</li><li>Rodrigues is the exponential map from lie algebra to lie group.</li></ul><h3>Step 3 — Full Pose (SE(3))</h3><h3>Concept</h3><p>A robot’s “pose” isn’t just about which way it’s facing — it’s the full package: <strong>rotation + translation</strong>. Rotation tells you the orientation, or how the robot is turned in space, while translation tells you its position, or where it is in space. Put them together, and you have everything you need to map a point from one coordinate frame to another.</p><p>Mathematically, this combination lives in a special group called <strong>SE(3)</strong> (Special Euclidean group in 3D), which represents all possible rigid motions in 3D — movements that don’t distort shapes, just shift and spin them. In practice, we store the rotation as a 3×3 matrix and the translation as a 3×1 vector, then bundle them into a 4×4 transformation matrix. This single object can take a point from, say, the robot’s local sensor frame and express it in the world frame with one clean multiplication. In SLAM, SE(3) is everywhere — every landmark, every keyframe, and every trajectory estimate boils down to these full pose transformations.</p><h3>The math</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*7L3dkX89tdgjfUrd3hTeeg.png" /></figure><h3>Why it matters for SLAM</h3><ul><li>Camera/robot poses live in SE(3).</li><li>Inverses and compositions are constant operations.</li></ul><h3>C++ example</h3><pre>#include &lt;Eigen/Core&gt;<br>#include &lt;Eigen/Geometry&gt;<br>#include &lt;iostream&gt;<br>#include &lt;cmath&gt;<br>using namespace Eigen;<br>using namespace std;<br><br>int main() {<br>    Matrix3d R = AngleAxisd(M_PI/4, Vector3d::UnitZ()).toRotationMatrix();<br>    Vector3d t(1, 3, 4);<br><br>    Isometry3d T = Isometry3d::Identity();<br>    T.linear() = R;<br>    T.translation() = t;<br><br>    Vector3d p_B(1, 0, 0);<br>    Vector3d p_W = T * p_B;<br>    cout &lt;&lt; &quot;p_W = &quot; &lt;&lt; p_W.transpose() &lt;&lt; &quot;\n&quot;;<br><br>    Isometry3d T_inv = T.inverse();<br>    Vector3d p_B_back = T_inv * p_W;<br>    cout &lt;&lt; &quot;p_B_back = &quot; &lt;&lt; p_B_back.transpose() &lt;&lt; &quot;\n&quot;;<br>}</pre><h3>Exercises</h3><ol><li>Set t=0→ pure rotation.</li><li>Set R=I → pure translation.</li><li>Compose two poses and check the result.</li></ol><h3>What to notice</h3><ul><li>Order matters in pose multiplication.</li><li>Inverse uses transpose for rotation, adjusted translation.</li></ul><h3>Math to internalize</h3><ul><li>Composition: T(AC)=T(AB)T(BC)</li><li>Inverse for rotation is R⊤ and for translation is −R⊤t</li></ul><h3>Step 4 — Rotation Conversions</h3><h3>Concept</h3><p>A single rotation can wear many different “outfits” — matrix, quaternion, or Euler angles — and each one has its own strengths. A <strong>rotation matrix</strong> is great for direct geometric transformations, but it takes up 9 numbers and can accumulate numerical drift if not kept orthonormal.</p><p><strong>Quaternions</strong> are a compact 4-number representation that avoid the dreaded “gimbal lock” and make smooth interpolation (like animation or gradual camera movement) easy.</p><p><strong>Euler angles</strong> — the familiar roll, pitch, and yaw — are the most human-readable, telling you “first tilt this much, then spin that much, then twist this much,” but they can be tricky because different conventions (order of rotations) give different results.</p><p>In robotics and SLAM, we often hop between these formats depending on the task: Euler for user interfaces, quaternions for smooth orientation updates, and matrices for actually transforming points. Knowing how to convert between them means you can work in whichever form makes your current problem easiest to handle, without losing the underlying rotation.</p><h3>Why it matters for SLAM</h3><ul><li><strong>Matrix</strong>: easy application to points.</li><li><strong>Quaternion</strong>: compact, stable, no gimbal lock (preferred in optimization).</li><li><strong>Euler</strong>: intuitive (yaw/pitch/roll), good for UI.</li></ul><h3>C++ example</h3><pre>#include &lt;Eigen/Core&gt;<br>#include &lt;Eigen/Geometry&gt;<br>#include &lt;iostream&gt;<br>using namespace Eigen;<br>using namespace std;<br><br>int main() {<br>    Matrix3d R = AngleAxisd(M_PI/4, Vector3d::UnitZ()).toRotationMatrix();<br>    Quaterniond q(R);<br>    Vector3d euler = R.eulerAngles(2, 1, 0); // ZYX order<br><br>    cout &lt;&lt; &quot;Quaternion (x,y,z,w): &quot; &lt;&lt; q.coeffs().transpose() &lt;&lt; &quot;\n&quot;;<br>    cout &lt;&lt; &quot;Euler ZYX (deg): &quot; &lt;&lt; (euler*180/M_PI).transpose() &lt;&lt; &quot;\n&quot;;<br><br>    Matrix3d R2 = q.toRotationMatrix();<br>    cout &lt;&lt; &quot;Back to matrix:\n&quot; &lt;&lt; R2 &lt;&lt; &quot;\n&quot;;<br>}</pre><h3>Exercises</h3><ol><li>Change axis and see how quaternion changes.</li><li>Convert quaternion → Euler → quaternion and compare.</li><li>Try 90° pitch → observe gimbal lock.</li></ol><h3>Math to internalize</h3><ul><li>Quaternion from axis–angle:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*f4bda5AVjz5SJfwF34qPKA.png" /></figure><ul><li>Euler order matters: eulerAngles(2,1,0) = ZYX.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13128f8699dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>