I'm mildly suspicious that this example is an implementation of a generic matrix functionality though: you couldn't patent this sort of work, because it's not patentable - it's a mathematics. It's fundamentally a basic operation, that would have to be implemented with a similar structure regardless of how you do it.
Patents and copyrights are totally different, and should be treated as such. The issue isn't about whether someone copies the algorithm, it's whether they copy the written code. Nothing in an algorithms textbook is patentable either, but if you copy the words describing an algorithm from it, you are stealing their description.
Only if it has physical consequences. There was a case in 2014 that narrowed software patents significantly, called "Alice vs CLS Bank." No more patents on computerized shopping carts, but encryption or compression can still be patented.