How to import and evaluate multiple files in matlab?

1 回表示 (過去 30 日間)
Natalie Arroyo-Rivera
Natalie Arroyo-Rivera 2021 年 9 月 14 日
回答済み: Mohammad Sami 2021 年 9 月 15 日
Hello,
This code works for importing file a1.DAT. I have a1, a2 and a3 files that I want to use for my code. How do I tell matlab to load all 3 files?
This is the code to load 1 single file. Any ideas?
function DATA=INPUT_FILES_2
global DATA
fid = fopen('a1.DAT','rt');
fgetl(fid);
DATA.data = fscanf(fid,'%f',[7, Inf]);
DATA.data = DATA.data';
DATA.xte = DATA.data(1,2);
DATA.rows_remove = find(DATA.data(:,2)>DATA.xte);
if (~isempty(DATA.rows_remove))
DATA.data = DATA.data(1:DATA.rows_remove(1)-1,:);
end
end

回答 (1 件)

Mohammad Sami
Mohammad Sami 2021 年 9 月 15 日
I am assuming all your data files have the same format. You should convert your current code into a function and call it 3 times with the different filenames. Also do not use global variable to store DATA.
% INPUT_FILES_2.m
function DATA=INPUT_FILES_2(filename)
fid = fopen(filename,'rt');
fgetl(fid);
DATA.data = fscanf(fid,'%f',[7, Inf]);
DATA.data = DATA.data';
DATA.xte = DATA.data(1,2);
DATA.rows_remove = find(DATA.data(:,2)>DATA.xte);
if (~isempty(DATA.rows_remove))
DATA.data = DATA.data(1:DATA.rows_remove(1)-1,:);
end
end
Now you can call this in your workspace or another script / function to load the 3 files or any number of files.
DATA_A1=INPUT_FILES_2('a1.DAT');
DATA_A2=INPUT_FILES_2('a2.DAT');
DATA_A3=INPUT_FILES_2('a3.DAT');

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by