Data Files and Character Strings
MATLAB Text Data Import
MATLAB text data import turns a file of written records into values you can use in calculations. Engineering instruments often export measurements beside sensor names, identifiers, and missing-reading markers. Your goal is to preserve what each field means while giving MATLAB an appropriate representation. A command that runs without an error has not necessarily interpreted the file correctly.
Read the file structure first
A delimiter is a character that separates fields within a record, such as a comma, semicolon, or tab. Before importing, inspect the header, several data records, decimal notation, and any introductory lines. Check which fields are measurements and which are labels. A digit-only identifier such as "0042" can still be text: its leading zeros may carry meaning.
A decimal separator has a different job from a delimiter. For example, a semicolon-delimited record containing a decimal comma could be 0042;2,75. It contains two fields; the second represents the number 2.75 under that decimal convention.
Choose a representation that preserves meaning
An import schema specifies how file fields become MATLAB variables, including their names, types, and missing-data rules. Choose the output according to the file's contents.
File contents and intended use | Suitable function | Result |
|---|---|---|
Mixed labels and measurements in columns | readtable | A table with separately typed variables |
A rectangular block of numeric measurements | readmatrix | A numeric array by default |
Raw text that you want to inspect | fileread | One character vector containing the file contents |
MATLAB distinguishes single-quoted character vectors, such as '2.75', from double-quoted string scalars, such as "2.75". Both contain text rather than a numeric measurement. A string array can hold a separate text value for each record.
For numeric text, str2double interprets the written number:
x = str2double('2.75');Here, x is the numeric value 2.75. In contrast, double('2.75') returns numeric character codes. Applying double to a string scalar behaves differently, so always identify the input type when reviewing conversion code.
Configure the import and check the result
For a comma-delimited file whose first line contains ProbeID and Voltage_mV, configure types before reading:
opts = detectImportOptions("bench.csv", "Delimiter", ",");
opts = setvartype(opts, "ProbeID", "string");
opts = setvartype(opts, "Voltage_mV", "double");
opts = setvaropts(opts, "Voltage_mV", "TreatAsMissing", "NA");
opts.MissingRule = "fill";
T = readtable("bench.csv", opts);Detection proposes a schema; inspect its variable names, types, and data lines rather than assuming they match the file. For a numeric double variable, the usual missing fill value is NaN. A missing reading is different from a measured zero. Likewise, str2double returns NaN for unconvertible text, so investigate unexpected conversions rather than silently discarding them.
Use head(T), summary(T), and height(T) to inspect sample records, variable summaries, and record count. Compare selected imported values with the original file. Dot notation such as T.Voltage_mV extracts that variable's contents.
Numeric import does not automatically convert physical units. For a voltage stored in millivolts, the governing conversion is
For example, an imported value of 325 mV represents 0.325 V. Make this conversion explicit in the variable name and calculation.
What to remember
- Inspect headers, delimiters, decimal notation, and missing markers before importing.
- Preserve identifiers as text and measurements as numeric variables.
- Configure important types explicitly, then validate records against the source.
- Treat missing readings and unit conversion explicitly.
Example: Importing a sensor log
A measurement system exports sensor.csv into MATLAB's current folder. The first line contains the variable names, and the following three lines contain data. The file uses commas as field delimiters and periods as decimal separators.
ProbeID | Voltage_mV |
|---|---|
0007 | 18.4 |
0008 | NA |
0012 | 21.6 |
The identifiers must retain their leading zeros. The instrument documentation defines NA as a missing reading.
a) Write MATLAB commands to import the file as a table, preserving identifiers as strings and storing voltages as double values. Represent the missing voltage as NaN and retain its record.
Detect the comma-delimited structure, then explicitly assign each variable's type. Configure the documented missing marker before reading the file. With a numeric double variable, the default missing fill value is NaN.
opts = detectImportOptions("sensor.csv", "Delimiter", ",");
opts = setvartype(opts, "ProbeID", "string");
opts = setvartype(opts, "Voltage_mV", "double");
opts = setvaropts(opts, "Voltage_mV", "TreatAsMissing", "NA");
opts.MissingRule = "fill";
T = readtable("sensor.csv", opts);The identifiers are read as "0007", "0008", and "0012". Setting their type before import preserves the digit sequences; converting numeric identifiers back to strings afterward would not recover their leading zeros.
b) Check the number of data records, the identifier type, and the number of missing voltage readings. State the expected results.
Check the imported structure and compare its contents with the source. The header provides variable names and is not a data record. The missing voltage should remain in the table rather than causing its record to disappear.
nRecords = height(T);
idType = class(T.ProbeID);
nMissing = sum(isnan(T.Voltage_mV));
head(T)The expected results are nRecords = 3, idType = 'string', and nMissing = 1. The voltage column contains ________ mV, NaN, and ________ mV in source order. Inspecting the IDs also confirms that their leading zeros survived.
c) Convert the voltage column to volts and calculate the arithmetic mean of the available readings. Exclude the documented missing reading and report the mean to four decimal places.
The file stores numerical values in millivolts, so convert them explicitly. Multiplying by the conversion factor leaves the missing entry as NaN. The requested mean uses the two available readings.
voltage_V = T.Voltage_mV * 1e-3;
meanVoltage_V = mean(voltage_V, "omitnan");Convert each available reading:
Then calculate the mean:
The denominator is two, not three, because the middle record contains no voltage reading. The result lies between the two available voltages, which provides a useful check.
An engineering laboratory stores the same file name in two MATLAB variables using different quotation marks. Complete the table with exact integers.
c = 'run_04.csv';
s = "run_04.csv";The function numel counts array elements, size(x,2) returns the number of columns in x, and strlength counts characters in text. Include the underscore and period when counting characters.
| Expression | Result for c | Result for s |
| numel | ||
| size in dimension 2 | ||
| strlength |
A pressure field has been extracted from a text file as the MATLAB character vector pText = '7.25';. The field represents pressure in kPa. Which statement creates a numeric scalar p_kPa equal to 7.25?