MATLAB Answers

0

Loading multiple mat files

Asked by Aftab Ahmed Khan on 7 Feb 2015
Latest activity Commented on by Stephen Cobeldick on 30 Oct 2018
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

  0 Comments

Sign in to comment.

2 Answers

Answer by Stephen Cobeldick on 7 Feb 2015
Edited by Stephen Cobeldick on 7 Feb 2015
 Accepted Answer

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)
load(filenames{kk})
end
Also note that I fixed the cell array indexing to use the correct {} braces , and removed the char operation which is completely unnecessary as the contents of the cell array filenames are already of class character.

  1 Comment

Thanks, it works.

Sign in to comment.


Answer by ELCIO S
on 30 Oct 2018

What about if I have many files with different names? How can I do to load all of them?

  1 Comment

"What about if I have many files with different names? How can I do to load all of them?"
Read the MATLAB documentation:

Sign in to comment.