Matlab code - Keep leading zero while extracting numerical data as string from .CSV

313 Views Asked by At

I have data stored in CSV format.The data contains numerical values formatted as text but written without any apostrophe.

Sample

I've tried to export the data using xlsread, bu Matlab automatically remove the leading zero. Is it possible to force Matlab to read it as string to keep the leading zero?

2

There are 2 best solutions below

1
Daniel On

xlsread has three outputs, the third bering the raw data. Use the third output, you will find the text there. Then you can convert the text to numeric data using str2num.

0
Andrew Janke On

If it's a CSV file, don't use xlsread. That's for Excel (.xls/.xlsx) files. If the base data is primarily actually in an Excel file, then don't save it to CSV; read the Excel file directly.

You're going to have to use a lower-level read routine like textscan or fscanf to read this in. The issue is that CSV files don't actually represent strings and numbers differently: CSV files only contain text data, so programs like Matlab that work like numbers have to provide some "magic" to decide what things look like numbers and convert those strings into numbers. And they figure that you don't care about stuff like leading zeroes, so they abstract that away. But in this case you do care, so you have to bypass their magic.

Don't worry; textscan and fscanf are easy to use.

Do something like this:

fid = fopen('myfile.csv');
col_vals = textscan(fid, '%s');
orig_policy_num = col_vals{1};
fclose(fid);

Terminology note: you say "The data contains numerical values", but numerical values represent numbers, and leading zeros are insignificant for numbers; that's just a matter of different styles in which the same value can be written. But you care about leading zeros. That means this is actually text data, not numeric data. And you want to read it as such.