How to split 36x1 cell array into 36x3 cell array?
Show older comments
I have the attached text file which I need to split into 3 columns.
First column will be 36x1 with elements # {which I do not need}
Second column should contain the sentences up to :
Third column will contain the data { Kinetic Energy, Counts per Second .......}
I am using the following code, but I end up with 36x1 cell and I could not seperate the columns.
Thank you very much in advance for your help!!
clear all
close all
FileName=sprintf('file.txt');
fid= fopen(FileName, 'rt');
tline = fgetl(fid);
header = cell(0,1);
while ischar(tline)
header{end+1,1} = tline
tline = fgetl(fid);
if strcmp(tline,' Workfunction: ')== 1
sprintf('end')
break
end
end
header = split(header(:,1),' ');
fclose(fid);
Accepted Answer
More Answers (1)
fid = fopen('file.txt');
data = fread(fid);
fclose(fid);
c_data = strsplit(char(data).',newline());
out = repmat({''},numel(c_data),3);
for i = 1:numel(c_data)
if isempty(c_data{i}) || c_data{i}(1) ~= '#'
continue
end
out{i,1} = '#';
idx = find(c_data{i} == ':',1);
if isempty(idx)
continue
end
out{i,2} = strtrim(c_data{i}(2:idx));
out{i,3} = strtrim(c_data{i}(idx+1:end));
end
disp(out);
1 Comment
Mohammed Qahosh
on 3 Jan 2022
And sorry for late reply, I had to wait to try it on my office 2021 Matlab. As I am still using 2017 on my personal laptop and with this version still I get en error.
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!