How can I create a for loop to remove certain columns from different numerical arrays?
1 回表示 (過去 30 日間)
古いコメントを表示
Alexander Simpson
2020 年 10 月 14 日
コメント済み: Alexander Simpson
2020 年 10 月 14 日
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!