user217285
user217285

Reputation: 366

Accessing variables from different files in matlab

I have a "data.m" file that contains a handful of large arrays that I do not want in my main file. For all intents and purposes, they are in the form

a1 = [1,2,3]
a2 = [3,4,5]

How can I access a1 and a2 from another script? Or should I be putting these in a .mat file? If so, how do I do that?

Upvotes: 0

Views: 559

Answers (3)

Crowley
Crowley

Reputation: 2331

Say we have data.m of Yours and a function foo.m that is about to use variables from there.

Turn the data.m into this form:

function[]=data()        % defines a function with no output nor input
a1=[1 2 3];
b2='string';
%Your definitions and other code

save('DataFile.mat');      % save EVERY varible used in the code with it's name

Then in foo.m

function[]=foo()
load('DataFile.mat');      % Load all variables saved in DataFile.mat

disp(b2);

You can also prevent temporary variables to be saved with the mandatory ones by deleting them just before save command by clear temp1 temp2
If you want to save some variables, say a1 in one file and other in different file You can use save('DataFile.mat','a1')

If you want to load specific variables You can use load('DataFile.mat','b1')

Upvotes: 0

Fayssal El Mofatiche
Fayssal El Mofatiche

Reputation: 1109

If the values of the variables are constant, it would be better to store these in MAT files. Also, try to use functions instead of scripts unless it is necessary to use scripts. Scripts define global variables which could lead to inadvertently overwriting variables among many other issues.

Upvotes: 1

Lincoln Cheng
Lincoln Cheng

Reputation: 2303

Heres an easy way:

Inside data.m, output your arrays:

function [a1, a2] = data( )
...
end

You can access these arrays from your "main" function (e.g thefunc.m) like this:

function [ ] = thefunc( )
//say you want to store array a1 into a variable X, and array a2 into variable Y
[X, ~] = data;
[~, Y] = data;
end

Of course, thefunc.m and data.m should be in the same working directory.

Upvotes: 2

Related Questions