Search code examples
matlabmatlab-load

load mat file in workspace


I have a folder A that contains folders B and C

A--B
   C--|
     --|mat file  

at the folder level, I have a startup scrit and I want from this script to load data available in data.mat file available in C1 folder.

so from my script A_script.m , I did :

load('C/C1/data.mat');

content of script file :

function data_startup
%WHC_PROJECT_STARTUP
bdclose all;
load('B\C\data_v2.0.mat');

but this does nothing,data not loaded and no error raised ! can someone help me ?

thanks


Solution

  • What I understand from the question is you have a data stored in a .mat-file in a sub-folder and you want to use it for a some kind of initialization. If you expect to use them later from the base workspace, then one possibility would be to change the function to a script:

    %WHC_PROJECT_STARTUP
    bdclose all;
    load(fullfile('B', 'C', 'data_v2.0.mat'));
    

    I would recommend here the use of the function

    fullfile('B', 'C', 'data_v2.0.mat')
    

    because this makes you code platform-independent (Linux uses '/', Windows '\'). If you want the content of the .mat-file loaded in you base workspace, just save the code above as script and execute it.

    If you insist to read the file in an function and use it later in base workspace, then look at the following code

    function data_startup()
    %WHC_PROJECT_STARTUP
    bdclose all;
    temp_data=load(fullfile('B', 'C', 'data_v2.0.mat')); % will be loaded as structure
    file_variables=fieldnames(temp_data);% get the field names as cell array
    for ii=1:length(file_variables)
       % file_variables{ii} - string of the field name
       % temp_data.(file_variables{ii}) - dynamic field reference
       assignin('base', file_variables{ii}, temp_data.(file_variables{ii}));
    end
    

    The code should work, right now I am at home and can not test it, sorry.

    I would prefer the script solution, assigning variables from one workspace to another could lead to problems with the support and the extension of the code (suddenly variables are created and you do not see where they come from). Here are some more examples how to access fields of a structure dynamically.