How can I create a for loop to remove certain columns from different numerical arrays?
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
Walter Roberson
2020년 10월 14일
편집: Walter Roberson
2020년 10월 14일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Adding custom doc에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!