× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Loading multiple .mat files containing the same variable name and changing the variable names simultaneously?

Ray Phan
Jul 02, 2015
<p>I would load each <code>.mat</code> file in sequence and put each of the corresponding calories as a separate field being all combined into a single <code>struct</code> for you to access. Given the directory of where these <code>.mat</code> files appear, do something like this:</p> <pre><code>%// Declare empty structure s = struct() folder = '...'; %// Place directory here %// Get all MAT files in directory f = dir(fullfile(folder, '*.mat')); %// For each MAT file... for idx = 1 : numel(f) %// Get absolute path to MAT file - i.e. folder/file.mat name = fullfile(folder, f(idx).name); %// Load this MAT file into the workspace and get the calories variable load(name, 'calories'); %// Get the name of the fruit, are all of the characters except the last 4 (i.e. .mat) fruit_name = f(idx).name(1:end-4); %// Place corresponding calories of the fruit in the structure s.(['calories_' fruit_name]) = calories; end </code></pre> <p>You can then access each of the calories like so using dot notation:</p> <pre><code>c = s.calories_apple; d = s.calories_orange; ... ... </code></pre> <p>... and so on.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31035540/Loading%20multiple%20.mat%20files%20containing%20the%20same%20variable%20name%20and%20changing%20the%20variable%20names%20simultaneously?/31035962">Stack Overflow</a>.</p>
comments powered by Disqus