split value in single cell
2 views (last 30 days)
Show older comments
Given a txt file, there are numbers in a single cell, eg. 2.02208101128e+11
and there are columns for that.
I want to make it into 5 columns so it will be 2022 08 10 11 28
How can I do that?
0 Comments
Accepted Answer
Image Analyst
on 8 Oct 2022
You forgot to attach your text file.
About all I can guess is this
% Extract the contents of the cell. The contents are presumably a character array.
cellContents = yourCellArray{index};
% Split apart character array and put into different columns
t{row, 1} = strrep(cellContents(1:5), '.', '');
t{row, 2} = cellContents(6:7);
t{row, 3} = cellContents(8:9);
t{row, 4} = cellContents(10:11);
t{row, 5} = cellContents(12:13);
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
3 Comments
Image Analyst
on 9 Oct 2022
Edited: Image Analyst
on 9 Oct 2022
This should work:
% Get a list of files
filePattern = fullfile(pwd, 'text f*.txt');
fileList = dir(filePattern);
numFiles = numel(fileList)
for fileNumber = 1 : numFiles
% Read in this particular file.
fullFileName = fullfile(fileList(fileNumber).folder, fileList(fileNumber).name);
fprintf('Reading in file #%d of %d.\n', fileNumber, numFiles);
data = readmatrix(fullFileName);
[rows, columns] = size(data);
if fileNumber == 1
% Declare output array with the number of rows that the first file has.
outDates = zeros(rows, 5);
rows1 = rows;
columns1 = columns;
end
% See that this file has the same number of rows and columns as the first file.
if rows ~= rows || (columns ~= columns1)
warningMessage = sprintf('Warning: this file does not match the first one:\n"%s"', fullFileName)
uiwait(warndlg(warningMessage));
% Skip it since something is wrong.
continue;
end
for row = 1 : rows
str = sprintf('%.15f', data(row, 1));
% Split apart character array and put into different columns
outDates(row, 1) = str2double(str(1:5));
outDates(row, 2) = str2double(str(6:7));
outDates(row, 3) = str2double(str(8:9));
outDates(row, 4) = str2double(str(10:11));
outDates(row, 5) = str2double(str(12:13));
outDates(row, fileNumber+5) = data(row, 2);
end
end
message = sprintf('Done processing %d files.', numFiles);
fprintf('%s\n', message);
uiwait(helpdlg(message))
More Answers (0)
See Also
Categories
Find more on Language Support in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!