lola
lola

Reputation: 5789

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

Upvotes: 1

Views: 8897

Answers (3)

Ivan Angelov
Ivan Angelov

Reputation: 353

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.

Upvotes: 1

zamazalotta
zamazalotta

Reputation: 433

You can modify your function to have an output like this, then in your parent(caller) function you can use the data in this output variable

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

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

The reason is because a function introduces its own variable scope.1 The variables from the .mat file will be loaded into the scope of the function, but not into the global scope.


1. See also http://www.mathworks.co.uk/help/techdoc/matlab_prog/f0-38052.html#f0-38463.

Upvotes: 3

Related Questions