Q: MatLab - Importing CSV text file that contains commas not meant to separate I have received a delivery of very large text files where the data has a comma that is from the the real data, not meant to separate the data. Below is my code and a data file example.
DATA FILE EXAMPLE(Line 5 is where the problem begins, 'Bubba1, TTR1' should not be separated):
Chan, Date, Time, SignalName, Mode#, Lat, Long,  
01, 12/12/12, 01:01:20.234, OFF, 0, 39.185, -106.85,  
01, 12/12/12, 01:01:20.345, OFF, 0, 39.185, -106.85,  
01, 12/12/12, 01:01:20.445, OFF, 0, 39.185, -106.85,  
01, 12/12/12, 01:01:20.545, Bubba1, TTR1, 1, 39.185, -106.85,  
01, 12/12/12, 01:01:20.645, Bubba1, TTR1, 1, 39.185, -106.85,  
01, 12/12/12, 01:01:20.745, Bubba1, TTR1, 1, 39.185, -106.85,   
01, 12/12/12, 01:01:20.845, OFF, 0, 39.185, -106.85,

My Code:
clear;clc;
fid = fopen('test.txt');
fileHeader = textscan(fid,'%s',1,'delimiter','\n','headerlines',0);
fileHeader = strread(char(fileHeader{:}),'%s','delimiter',',')';
fileHeader = strrep(fileHeader,' ','');
fileHeaderLength=length(fileHeader);
format = repmat('%s',1,fileHeaderLength);
data = textscan(fid,format,'delimiter',',');
data=[data{:}];


A: I think this is a case where you just need to if statement and while loop it.
The commas at the end of the line make it more complicated.
clear;clc;
fid = fopen('test.txt');
fileHeader = textscan(fid,'%s',1,'delimiter','\n','headerlines',0);
fileHeader = strread(char(fileHeader{:}),'%s','delimiter',',')';
fileHeader = strrep(fileHeader,' ','');

data = fileHeader;
line = {''};

while ~isempty(line)
    line = textscan(fid,'%s',1,'delimiter','\n','headerlines',0);
    line = strread(char(line{:}),'%s','delimiter',',')';
    if length(line) > length(fileHeader)
        line = {line{1:3}, strjoin(line(4:end-3), ', '), line{end-2:end}};
    end

    data=vertcat(data, line);
end

fclose(fid);


A: Add these lines to your code:
for k= size(data,1):-1:1
    if strcmp(data{k,2},'')
        data{k-1,4}=[data{k-1,4} ',' data{k-1,5}];
        data{k-1,5}=data{k-1,6};
        data{k-1,6}=data{k-1,7};
        data{k-1,7}=data{k,1};
        data(k,:)=[];
    end
end

