MATLAB: How to create a for loop to remove certain columns from different numerical arrays

import dataloops

I have a series of plain text files that I need to import into matlab. Matlab imports these files as numerical arrays, and I only want the 3rd and 5th columns of each file. I have a for loop that imports each file into matlab and makes it a numerical array, but I want to take that further and remove the columns I don't want, and then save the new files back to the directory. Here's the code I have so far:
>> files = dir('*.pck'); %this creates a string of all the files of a specific extension
% in a directory. This part works fine.
>> for i=1:21 %just the number of files I have in this specific case. This also works fine.
eval(['load ' files(i).name]); %I was only able to do this after 3 hours of googling.
% It loads the files, makes each one a variable with the file's name as the variable name,
% it works perfectly.
If I end the loop there then all the files I need are loaded and I can filter each one and save each one by hand, but it feels like I should be able to do this with a loop, I just don't know how to do it. The only thing I can think to try is:
files(i).name = files(i).name(:,[3,5]);
in the same loop hoping it would do make new variables with only the 3rd and 5th columns, but that doesn't work.
Any help at all would be greatly appreciated.

Best Answer

  • projectdir = '.'; %or directory where the files are
    dinfo = dir('*.pck');
    filenames = fullfile(projectdir, {dinfo.name});
    nfiles = length(filenames);
    for K = 1 : nfiles
    thisfile = filenames{K};
    thisdata = load(thisfile, '-ascii');
    thisdata = thisdata(:,[3 5]);
    [~, basename, ~] = fileparts(thisfile);
    newname = fullfile(projectdir, [basename '.txt']);
    save(newname, 'thisdata', '-ascii');
    end
    No dynamic variable names used.