Matlab-使用数字和文本列读取数据

Matlab-使用数字和文本列读取数据,matlab,csv,Matlab,Csv,通常我使用load或csvread加载数据。现在,我需要使用以下结构加载数据: 0.1, 0.2, 0.3, 0.4, some_text 0.5, 0.6, 0.7, 0.8, some_text2 ... 在这种情况下,load和csvread都是无用的,因为它们只能读取数值。我发现我可以像这样使用readtable: readtable('file.txt', 'Delimiter', ',', 'Format', '%f%f%f%f%s'); 现在我有两个问题: 1) readtab

通常我使用
load
csvread
加载数据。现在,我需要使用以下结构加载数据:

0.1, 0.2, 0.3, 0.4, some_text
0.5, 0.6, 0.7, 0.8, some_text2
...
在这种情况下,
load
csvread
都是无用的,因为它们只能读取数值。我发现我可以像这样使用
readtable

readtable('file.txt', 'Delimiter', ',', 'Format', '%f%f%f%f%s');
现在我有两个问题:

1)
readtable
假设我的文件有头,我少了一行数据

2) 数据存储在Nx4表中,而不是Nx4双矩阵中

解决这两个问题有什么帮助吗?在我的例子中有没有更有用的函数


编辑:最后,我只需要从文件(第1:4列)中加载数值就可以了。

这应该可以了。假设您保存了
/input.txt

1.1, 2.2, 3.3, 4.4, Hello world
6.6, 7.7, 8.8, 9.9, How are you
要阅读本文,请使用Matlab原生逐行解析函数
textscan
;此处,'%s'表示()。 它被另一个细胞包裹着。提取只有一个元素的单元格
hold_cell
,我们在
中有一个
N
乘以1个单元格
x_。
剩下的很简单,如果我们回忆起一个字符串只是一个字符数组的话

fid = fopen('./input.txt');
hold_cell = textscan(fid, '%s', 'Delimiter', '\n');
x_in = hold_cell{1,1};
hold_size=size(x_in);
N=hold_size(1,1);

y_out =zeros(N,4);
for i=1:1:N
   hold_idx =strfind( x_in{i}, ',' );% those positions of comma
   y_out(i,1) =str2num( x_in{i,1}( 1 : hold_idx(1)-1 ) );% 1st number
   y_out(i,2) =str2num( x_in{i,1}( hold_idx(1)+1 : hold_idx(2)-1 ) );%2nd number
   y_out(i,3) =str2num( x_in{i,1}( hold_idx(2)+1 : hold_idx(3)-1 ) );%3rd number
   y_out(i,4) =str2num( x_in{i,1}( hold_idx(3)+1 : hold_idx(4)-1 ) );%4th number
end

disp(y_out);
输出:

1.1000    2.2000    3.3000    4.4000
6.6000    7.7000    8.8000    9.9000

将代码中的
readtable
替换为
textscan
,您就快到了

使用示例file.txt

用文本扫描阅读

fid = fopen('file.txt');
data = textscan(fid, '%f%f%f%f%s', 'Delimiter', ',');
fclose(fid);
然后可以从前4列中收集数据

dataValues = [data{1:4}]
dataValues =
          0.1          0.2          0.3          0.4
          0.5          0.6          0.7          0.8

不是选民,但我不知道用这个。我需要从文件中加载数据。
dataValues = [data{1:4}]
dataValues =
          0.1          0.2          0.3          0.4
          0.5          0.6          0.7          0.8