How to import and evaluate multiple files in matlab?

조회 수: 2 (최근 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 CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by