简体   繁体   English

将文本文件读入matlab

[英]reading a text file into matlab

I keep trying to read a text file into matlab. 我一直试图将文本文件读入matlab。
A sample of the text file is as shown below: 文本文件的示例如下所示:

Sequence,rank,discipline,sincephd,service,sex,salary 顺序,等级,学科,辛苦,服务,性,工资
1,Prof,B,19,18,Male,139750 1,教授,B,19,18,男性,139750
2,Prof,B,20,16,Male,173200 2,Prof,B,20,16,Male,173200
3,AsstProf,B,4,3,Male,79750 3,AsstProf,B,4,3,男性,79750

My code is as shown: 我的代码如下所示:

clc
clear all
DELIMITER = ',';
HEADERLINES = 1;
% Import the file
newData1 = importdata('afifi.txt', DELIMITER, HEADERLINES);
% Create new variables in the base workspace from those fields.
vars = fieldnames(newData1);
for i = 1:length(vars)
    assignin('base', vars{i}, newData1.(vars{i}));
end

For some reason it will not read the last column properly. 由于某种原因,它将无法正确读取最后一列。 It only reads the first value in the first row, then does not read the rest of the last column. 它仅读取第一行中的第一个值,然后不读取最后一列的其余部分。 Anyone please tell me how to fix this! 有人请告诉我该如何解决!

You can use readtable to easily import a textfile with mixed data. 您可以使用readtable轻松导入具有混合数据的文本文件。 The line would be as follows: 该行如下所示:

readtable('afifi.txt','Delimiter',DELIMITER,'ReadVariableNames',true);

After you can replace fieldnames(newData1) with newData1.Properties.VariableNames to get the columnnames. 之后,你可以替换fieldnames(newData1)newData1.Properties.VariableNames得到COLUMNNAMES。 Put together, the code from your question works as desired: 综上所述,问题中的代码可以按需工作:

clc
clear all
DELIMITER = ',';
% Import the file
newData1 = readtable('afifi.txt','Delimiter',DELIMITER,'ReadVariableNames',true);
% Create new variables in the base workspace from those fields.
vars = newData1.Properties.VariableNames;
for i = 1:length(vars)
    assignin('base', vars{i}, newData1.(vars{i}));
end

If you rename afifi.txt to afifi.csv , you can do this, 如果您将afifi.txt重命名为afifi.csv ,则可以执行此操作,

[num, txt, all] = xlsread('afifi.csv');

And get everything in all 并获得一切all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM