Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

How can I share variables between .m files?

Asked by Nathan

Nathan (view profile)

on 14 Nov 2013
Latest activity Commented on by The Matlab Spot

The Matlab Spot (view profile)

on 14 Nov 2013

I am having trouble returning values to different .m files.

I have tried to declare the variables globally but that doesn't work.

The only way I have found to work is to use the:

save('') and load('') 

commands.

I know there must be a way without creating this variable file...

For example say I have a file name test.m with code:

function val = test(x)
y=x+5;
end

and then I make another file called test2.m with code:

test(5)
w=y+5

and then when I go to

run('test2.m') 

it says undefined function or variable 'y'.

How can i fix this without using save/load variables.

THANKS!

0 Comments

Nathan

Nathan (view profile)

Products

2 Answers

Answer by The Matlab Spot

The Matlab Spot (view profile)

on 14 Nov 2013

Okay.. You have done two mistakes with this...

1: In the file test.m, the function shall be

function val = test(x)
val=x+5;
end

receive the sum in the output variable of the function i.e. 'val'

2: In the file test2.m, the code shall be

y = test(5);
w=y+5;

receive the output of the function in 'y' before using it

0 Comments

The Matlab Spot

The Matlab Spot (view profile)

Answer by Nathan

Nathan (view profile)

on 14 Nov 2013

what if I have two random random numbers that are generated by test.m and I want to use both those values for test2.m

Say:

function val=test(x)
p=randi(x);
q=randi(x+1);
w=p*q;
h=p+q;
end

then test2.m has:

test(10)
r=w+5
t=h+5

1 Comment

The Matlab Spot

The Matlab Spot (view profile)

on 14 Nov 2013
function [w,h]=test(x)
p=randi(x);
q=randi(x+1);
w=p*q;
h=p+q;
end

then test2.m has:

[w,h] = test(10)
r=w+5
t=h+5

and so on...

for more detail MATLAB Documentation - Functions

Nathan

Nathan (view profile)

Contact us