Importing data without using read functions

1 回表示 (過去 30 日間)
Andromeda
Andromeda 2022 年 7 月 14 日
コメント済み: Jan 2022 年 7 月 15 日
I have heterogenous data (see textfile) and I am trying to modify my code such that it gives the same output as readtable('kimetsu.txt') and then finally readcell('kimetsu.txt'). I need help modifying it
Text = 'kimetsu.txt';
request = fopen(Text);
clear t
while ~feof(request)
line = string(fgetl(request));
line = line.split(",")';
line = array2table(line);
if exist("t","var")
t = [t; line];
else
t = line;
end
end
for j = 1:width(t) %this is the crucial part (I think) when it comes to modifying the code
t.(j) = str2double(t{:,j});
end
desired output without using readcell
ans =
5×5 cell array
{'Corps members'} {'Names' } {'Nichirins'} {'Lcs'} {'Sw'}
{[ 1]} {'Shenobu'} {[ 99]} {[ 23]} {[67]}
{[ 2]} {'Rengoku'} {[ 78]} {[ 10]} {[23]}
{[ 3]} {'Tanjiro'} {[ 10]} {[ 21]} {[98]}
{[ 4]} {'Akaza' } {[ 500]} {[ 89]} {[11]}

回答 (1 件)

Jan
Jan 2022 年 7 月 14 日
編集済み: Jan 2022 年 7 月 14 日
T = fileread(Text);
C = strsplit(T, newline);
Head = strsplit(C{1}, ',');
Body = reshape(split(C(2:end), ','), numel(C) - 1, []);
Num = str2double(Body);
Body(~isnan(Num)) = num2cell(Num(~isnan(Num)));
Result = [Head; Body]
Result = 5×5 cell array
{'Corps members'} {'Names' } {'Nichirins'} {'Lcs'} {'Sw'} {[ 1]} {'Shenobu'} {[ 99]} {[ 23]} {[67]} {[ 2]} {'Rengoku'} {[ 78]} {[ 10]} {[23]} {[ 3]} {'Tanjiro'} {[ 10]} {[ 21]} {[98]} {[ 4]} {'Akaza' } {[ 500]} {[ 89]} {[11]}
  2 件のコメント
Andromeda
Andromeda 2022 年 7 月 14 日
Hi Jan. I am getting an error
Error using split (line 99)
Element 5 of the text contains 0 delimiters while the previous elements have 4. All
elements must contain the same number of delimiters.
Error in Untitled (line 5)
Body = reshape(split(C(2:end), ','), numel(C) - 1, []);
Jan
Jan 2022 年 7 月 15 日
This does not happen for me, if I use the input you have provided. If you use another input, please post it.
Maybe your file contains blank lines ate the end? Then:
T = fileread(Text);
C = strsplit(T, newline);
C(cellfun('isempty', C)) = []; % Inserted line

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by