function test
inputFile = 'input.csv';
outputFile = 'output.csv';
totalColumns = 4;
rowBegin = 2;
rowEnd = 3;
columnBegin = 2;
columnEnd = 3;
delimiter = ';';
extractdata(inputFile, outputFile, totalColumns, rowBegin, rowEnd, columnBegin, columnEnd, delimiter);
function extractdata(inputFile, outputFile, totalColumns, rowBegin, rowEnd, columnBegin, columnEnd, delimiter)
fid = fopen(inputFile, 'r');
headerLines = fgetl(fid);
if strcmp(headerLines(end), delimiter)
headerLines = headerLines(1:end-1);
end
headerLines = textscan(headerLines, [repmat('%*s', 1, columnBegin - 1) repmat('%s', 1, columnEnd - columnBegin + 1) repmat('%*s', 1, totalColumns - columnEnd)], 'Delimiter', delimiter, 'CollectOutput', 1);
headerLines = headerLines{1,1};
C = textscan(fid, [repmat('%*d', 1, columnBegin - 1) repmat('%d', 1, columnEnd - columnBegin + 1) repmat('%*d', 1, totalColumns - columnEnd)], rowEnd, 'Delimiter', delimiter, 'CollectOutput', 1);
fclose(fid);
C = C{1,1};
C = C(rowBegin:rowEnd,:);
headerLines = cellfun(@(x)sprintf(['%s' delimiter],x), headerLines, 'UniformOutput', false);
headerLines = cell2mat(headerLines);
headerLines = [headerLines(1:end-1) '\n'];
fid = fopen(outputFile, 'wt');
fprintf(fid, headerLines);
fclose(fid);
dlmwrite(outputFile, C, '-append', 'delimiter', delimiter, 'precision', '%d', 'newline', 'pc');
Best Answer