It appears to work fine for me.
Note: in order to use a "function", the code for the function must be written in to a .m file and that .m file must start with the word "function" (or sometimes "classdef"). It is not allowed to enter a function at the command prompt, and it is not allowed to have a "function" in a .m file that starts with executable code such as an assignment.
You can store from "function x = twogrid" onward in a file named twogrid.m . Or you can store everything in one .m file, provided that you start that .m file with
function TheNameOfTheFileGoesHere
For example I used
function test258671
and stored it all in test258671.m