1
votes

I need to import a .txt datafile into Matlab. The file has been made into 3 columns. Each column has specific numbers for a given variable. The script code must be able to do the following,

Requirement

1) import the data from txt into Matlab

2) Matlab should remove the values from the columns if the values are out of a certain range

3) Matlab should tell which line and what type of error.

My Approach

I have tried using the following approach,

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

Problem

The above code has the following problems:

1) Matlab is not saving the imported data as 'data' after the user inserts the name of the file. Hence I don't know why my code is wrong.

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

2) The columns in the end do not have the same dimensions because I can see that Matlab removes values from the columns independently. Therefore is there a way in which I can make Matlab remove values/rows from a matrix rather than the three 'vectors', given a range.

1

1 Answers

0
votes

1) Not sure what you mean by this. I created a sample text file and Matlab imports the data as data just fine. However, you are only returning the original unfiltered data so maybe that is what you mean??? I modified it to return the original data and the filtered data.

2) You need to or the bad indices together so that they are removed from each column like this. Note I made some other edits ... see comments in the code below:

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

Note: you mentioned you want to know which line for which type of error. That information is now contained in badIDx1,2, 3. So you can return them, print a message to the screen, or whatever you need to display that information.