【问题标题】:Importing a txt file into Matlab and reading the data将txt文件导入Matlab并读取数据
【发布时间】:2018-04-12 00:45:43
【问题描述】:

我需要将一个 .txt 数据文件导入 Matlab。该文件已被制作成 3 列。每列都有给定变量的特定数字。脚本代码必须能够做到以下几点,

要求

1) 将txt中的数据导入Matlab

2) 如果值超出一定范围,Matlab 应该从列中删除值

3) Matlab 应该告诉哪一行和什么类型的错误。

我的方法

我尝试过使用以下方法,

function data = insertData(filename)
filename = input('Insert the name of the file: ', 's');
data = load(filename);

Column1 = data(:,1);
Column2 = data(:,2);
Column3 = data(:,3);

%Ranges for each column
nclm1 = Column1(Column1>0);
nclm2 = Column2(Column2 >= 10 & Column2 <= 100);
nclm3 = Column3(Column3>0);

%Final new data columns within the ranges
final = [nclm1, nclm2, nclm3];

end

问题

以上代码存在以下问题:

1) 用户插入文件名后,Matlab 不会将导入的数据保存为“数据”。因此我不知道为什么我的代码是错误的。

filename =input('Insert the name of the file: ', 's');
    data = load(filename);

2) 最后的列没有相同的维度,因为我可以看到 Matlab 独立地从列中删除值。因此,有没有一种方法可以让 Matlab 从矩阵中删除值/行,而不是在给定范围的情况下从三个“向量”中删除。

【问题讨论】:

    标签: matlab matrix


    【解决方案1】:

    1) 不确定你的意思。我创建了一个示例文本文件,Matlab 将数据导入为data 就好了。但是,您只返回原始未过滤的数据,所以也许这就是您的意思???我对其进行了修改以返回原始数据和过滤后的数据。

    2) 您需要将错误的索引or 放在一起,以便像这样从每一列中删除它们。注意我做了一些其他的编辑...见下面代码中的 cmets:

    function [origData, filteredData]= insertData(filename)
    % You pass in filename then overwrite it ... 
    % Modified to only prompt if not passed in.
    if ~exist('filename','var') || isempty(filename) 
        filename = input('Insert the name of the file: ', 's');        
    end
    origData = load(filename);
    
    % Ranges check for each column
    % Note: return these if you want to know what data was filter for 
    % which reason
    badIdx1 = origData(:,1) > 0;
    badIdx2 = origData(:,2) >= 10 & origData(:,2) <= 100;
    badIdx3 = origData(:,3)>0;
    
    totalBad = badIdx1 | badIdx2 | badIdx3;
    
    %Final new data columns within the ranges
    filteredData = origData(~totalBad,:);
    
    end
    

    注意:您提到您想知道哪种类型的错误对应哪一行。该信息现在包含在badIDx1,2, 3 中。因此您可以返回它们、在屏幕上打印一条消息,或者您需要显示该信息的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 2015-03-17
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多