Template output when grouping matrix blocks
If by grouping you mean wrapping each groups in a &lt;div&gt; for example, this should do it for you:

{% set groupCount = 0 %}
{% for block in entry.blocks %}

    {% switch block.type %}
        {% case "headingBlock" %}
            {{ groupCount &gt; 0 ? '&lt;/div&gt;' }}&lt;div&gt;
            {{ block.header }}
            {% set groupCount = groupCount + 1 %}

        {% case "richtextBlock" %}
            {{ block.richtext }}

        {% case "imageBlock" %}
            {{ block.image.one().url }}
    {% endswitch %}

{% endfor %}
&lt;/div&gt;


Changing the fields/blocks name accordingly of course.