Reading certain columns of data bigger than a number into one array smaller into another
1 view (last 30 days)
Show older comments
I have multiple .dat files, each of them has five columns. I only need the fifth columns and want to combine all numbers into two arrays : One only has numbers bigger than 0.7 and the other only has numbers smaller. Here is an example of .dat file
Here is the code I have so far. However, it seemed not work as expected. clc;
flist = dir(['./*.dat']); namelist = {}; for i = 1:length(flist) currentname = flist(i).name; namelist{end+1} = currentname; end
for i = 1:length(namelist) filename = namelist{i}; data = load(filename); High = data(data(:, 5)>0.7) Low = data(data(:, 5)<0.7) end Can anyone suggest a good way to work this out?
0 Comments
Accepted Answer
Voss
on 11 Dec 2021
Here is the code you posted:
clc;
flist = dir(['./*.dat']);
namelist = {};
for i = 1:length(flist)
currentname = flist(i).name;
namelist{end+1} = currentname;
end
for i = 1:length(namelist)
filename = namelist{i};
data = load(filename);
High = data(data(:, 5)>0.7)
Low = data(data(:, 5)<0.7)
end
This will store values from the first column of data into the variables High and Low, because the indexing into data has no column index specified. To store values from the fifth column of data, you can do this instead:
clc;
flist = dir(['./*.dat']);
namelist = {};
for i = 1:length(flist)
currentname = flist(i).name;
namelist{end+1} = currentname;
end
for i = 1:length(namelist)
filename = namelist{i};
data = load(filename);
High = data(data(:, 5)>0.7, 5)
Low = data(data(:, 5)<0.7, 5)
end
Now, High and Low have values from the fifth column of data, but they are overwritten each time through the loop. In order to accumulate these values into two arrays with values from all the files, you can do what David Hill suggests in his answer:
clc;
flist = dir(['./*.dat']);
namelist = {};
for i = 1:length(flist)
currentname = flist(i).name;
namelist{end+1} = currentname;
end
High = [];
Low = [];
for i = 1:length(namelist)
filename = namelist{i};
data = load(filename);
High = [High; data(data(:, 5)>0.7, 5)];
Low = [Low; data(data(:, 5)<0.7, 5)];
end
More Answers (1)
David Hill
on 9 Dec 2021
for i = 1:length(namelist)
filename = namelist{i};
data = readmatrix(filename);%try readmatrix
High = [High;data(data(:, 5)>0.7)];%do you want to combine them
Low = [Low;data(data(:, 5)<0.7)];
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!