Main issue is that the sample code is a bad practice. Once created by detectImportOptions, the options don't get updated based on the file if you change a property. So if you're updating delimiter, you're still using all other detected parameters which were not based on that delimiter.
opts = detectImportOptions(filename);
opts.VariableNamesLine = 1;
Try this instead of setting the delimiter after the fact.
opts = detectImportOptions(filename,'Delimiter',',');
detectImportOptions uses the parameters passed into it to do better detection. So instead of trying to guess the delimiter, it knows ',' is the anwser, so it detects the headerlines, variables, datatypes, etc. based on comma. It may also be faster.