matlabsaveloadworkspace

load .mat file, but not on the workspace


if contains(p_path, 'left')
    save(left_path', 'a', 'b', 'c', 'd');
    a = load(left_path);
elseif contains(p_path, 'right')
    save(right_path', 'a', 'b', 'c', 'd');
    b = load(right_path);
end

left_path is defined as below (base path is like 'C:\Users\Documents')

left_mean_data_path = [base_path, '\left_data.mat'];

Running this code, I checked that file is created at correct folder with correct name (left_path), Which means that 'save' works well. However, 'load' those not work. the file 'left_data.mat' or variables 'a', 'b', 'c', 'd' are not in the workspace.

To get those variables into workplace, I have to click the 'left_data.mat' file directly.

Can anyone help me??


Solution

  • The syntax data = load(filename) will load the contents of that matfile to a struct data. So inside data, you will find all the variables you saved.

    However, if you execute this line in a function, the data will be loaded in the workspace of that function, and not the base workspace. Read base and function workspaces and share data between workspaces.

    The easiest method to get the data to the base workspace is to use assignin in the function. In your function, you would do:

    function myfunction()
        data = load(filepath);
        assignin('base', 'data',data); % base workspace, variable name in base workspace, variable to assign in base workspace
    end