Why don't you do something like this? You can use switch and case to change the output of each part of the matrix (we call them blocks).
This is part of a snippet we use on Craft Plus to output a documentation matrix that contains code, titles, content etc.
{% for block in entry.documentation %}
{% switch block.type %}
{% case 'subsectionTitle' %}
<h2 id="{{ anchor }}">{{ block.subsectionTitle }} <a href="#{{ anchor }}" class="pound">#</a></h2>
{% case 'description' %}
<div class="docs-description">{{ block.description }}</div>
{% endswitch %}
{% endfor %}