Tosmai
Tosmai

Reputation: 60

Passing a variable out of local functions

I'm having some trouble with local functions within my code so I've pasted a simple example below:

function [avg,testvar] = test(x)     %Warning
n = length(x);
avg = mymean(x,n);
end

function [a,testvar] = mymean(v,n)
a = sum(v)/n;
testvar=123;
end

One can probably see what I'm attempting; to pass testvar out of the local functions. However Matlab returns the warning:

"The function return value 'testvar' might be unset"

with respect to the line I've commented "%Warning".

What's the best way of getting around this?

Upvotes: 0

Views: 535

Answers (2)

Shanqing Cai
Shanqing Cai

Reputation: 3876

You need to specify the value of the second output of test(). Otherwise how can MATLAB know what its value is supposed to be? It doesn't know the second output of mymean() should be routed to the second output of test(). Perhaps this will solve your problem.

function [avg,testvar] = test(x)     %Warning
  n = length(x);
  [avg, testvar] = mymean(x,n);
end

function [a,testvar] = mymean(v,n)
  a = sum(v)/n;
  testvar=123;
end

Upvotes: 4

Simon
Simon

Reputation: 32873

The variables between brackets after function are the output variables.

In your first function, you did not assign any value to testvar hence the warning. If you add testvar = 123; in the first function, the warning goes away. Or you can remove testvar from the output variables, leaving:

function avg = test(x)

Upvotes: 0

Related Questions