Very handy utility, but unfortunately the way MATLAB finds these serial ports does not take into account if other programs are using them - although fopen will of course prevent you from using that port. Also, when I incorporated it into a GUI, it did not stand up to being run a second time - it could not access the error message which instead replies with a 0x1 structure.
Nice work Daniel - clever to catch the error message. I was thinking this myself but did not have time to work it out.
I think, however that the code could be further improved by inserting these two lines after the first "end":
This removes the unnecessary handle and does not confuse the future operations with the serial port.