Filter löschen
Filter löschen

Loading multiple mat files

146 Ansichten (letzte 30 Tage)
Aftab Ahmed Khan
Aftab Ahmed Khan am 7 Feb. 2015
Kommentiert: Arif Hoq am 20 Dez. 2021
Hello everyone, i want to load this 3 set of data files into matlab using for loop but it is not working for me. Any help...............
clear all;
close all;
clc;
datafile={'data1.mat' 'data2.mat' 'data3.mat'};
num_schemes=3;
for sno=1:num_schemes
files = char(data(sno));
load files
end

Akzeptierte Antwort

Stephen23
Stephen23 am 7 Feb. 2015
Bearbeitet: Stephen23 am 16 Mär. 2021
You are getting confused between the command syntax and the function syntax. In particular you are trying to use the command syntax with a variable named files, which will never work as the line of code
load files
is interpreted as
load('files')
Where 'files' is treated as a string, not a variable. This is specifically explained in the load documentation: Do not use command form when any of the inputs, such as filename, are variables. The easiest solution is do not use the command syntax in your code, only use the function syntax and then you will never face this problem again. Try this instead:
filenames = {'data1.mat','data2.mat','data3.mat'};
for kk = 1:numel(filenames)
S = load(filenames{kk}) % Best to load into an output variable.
..
end
Also note that I fixed the cell array indexing to use the correct {} braces , removed the char operation which is completely unnecessary as the contents of the cell array filenames are already of class character, and for robustness loaded the file data into an output variable (which is a scalar structure).
  8 Kommentare
Stephen23
Stephen23 am 17 Dez. 2021
@Mohammad Ariful Hoq: yes, use comma-separated lists:
For example, to get the 'a' variable from all files into one array:
a = [S.a] % or VERTCAT or HORZCAT
Arif Hoq
Arif Hoq am 20 Dez. 2021
thank you very much@Stephen

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

ELCIO S
ELCIO S am 30 Okt. 2018
What about if I have many files with different names? How can I do to load all of them?
  1 Kommentar
Stephen23
Stephen23 am 30 Okt. 2018
Bearbeitet: Stephen23 am 17 Dez. 2021
"What about if I have many files with different names? How can I do to load all of them?"
Use DIR or SPRINTF:

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by