MATLAB: How to convert the .txt file into .mat file

text;

Best Answer

fid = fopen('YourInputFile.txt', 'rt');
header_line = fgetl(fid);
var_names = matlab.lang.makeValidName( regexprep(regexp(S,'[;,]','split'), '"', '') );
line_fmt = repmat('%g', 1, length(var_names));
datacell = textscan(fid, line_fmt, 'CollectOutput', 1, 'Delimiter', ',');
fclose(fid);
your_data = array2table( datacell{1}, 'VariableNames', var_names);
save('YourOutputFile.mat', 'header_line', 'your_data');
The column names used in the table would end up being
NumberOfTimesPregnant, PlasmaGlucoseConcentration, DiastolicBloodPressure, TricepsSkinFoldThickness, x2_HourSerumInsulin, BodyMassIndex, DiabetesPedigreeFunction, Age, ClassVariable
These are somewhat natural except for the x2_HourSerumInsulin, which is the result of automatically processing "2-Hour serum insulin" (double-quotes included) to create a valid MATLAB variable name, as column names for table() objects must be valid variable names.
If you have preferred variable names for the columns, you can replace the assignment to var_names with your preferred names; this code is generalized to build valid names from a header line with comma or semi-colon separator, under the assumption that the data is numeric. (The code will, however, fail if there are duplicate column headers.)