MATLAB: How to paste text to function

copytext;

Hi all,
I have this file mat.txt with cell array format:
year,month,day,hour,hst,doy,TempAvg,TempLow,TempHigh,HumAvg,HumLow,HumHigh,BaroAvg,BaroLow,BaroHigh,Windspeed,Gust,WindDirection,IntervalPrecip,SolarRadiationAvg,InsideTempAvg,InsideTempLow,InsideTempHigh,HeatIndex,WindChill,DewPoint,StationVoltage,wetbulb
I want to put the text above to the in the fucntion:
function textread(file)
[year,month,day,hour,hst,doy,TempAvg,TempLow,TempHigh,HumAvg,HumLow,HumHigh,BaroAvg,BaroLow,BaroHigh,Windspeed,Gust,WindDirection,IntervalPrecip,SolarRadiationAvg,InsideTempAvg,InsideTempLow,InsideTempHigh,HeatIndex,WindChill,DewPoint,StationVoltage,wetbulb] =...
textread(file,'%f %f %f %s %f %f %f %f %f %f %f %f %f %f %f %f %f','delimiter',',');
Can you help me to write code to copy text in txt file and paste it in the textread fuction?
I tried to use fprintf, textscan but it doesn't work with mix text like this
Thank you so much

Best Answer

S = fileread('mat.txt');
words = regexp(S, '\s*,\s*', 'split');
adjusted_words = matlab.lang.makeValidName, 'ReplacementStyle', 'delete');
varnames = string(matlab.lang.makeUniqueStrings(adjusted_words));
funname = 'my_textread';
fun_file = [funname, '.m'];
fid = fopen(fun_file, 'w');
fprintf(fid, 'function %s(file)\n', funname);
fprintf(fid, '[');
fprintf(fid, '%s,', varnames(1:end-1));
fprintf(fid, '%s] = ', varnames(end));
fprintf(fid, "textread(file, '%f %f %f %s %f %f %f %f %f %f %f %f %f %f %f %f %f','delimiter',',');\n");
fclose(fid);
clear(funname) %needed to get previous version out of working memory
You will now have my_textread.m containing a file that assigns the the variables whose name are contained in mat.txt, except cleaned up to remove spaces and to make sure that all of the names are unique.
For the purposes of this code you do not need to change your mat.txt file.