简体   繁体   中英

Matlab - using undefined function/value within function

Lets start with an example. Define a 1-D vector in the base Workspace:

q = [1 0 2 4 2 3 4 2 1 0 2]; % Defined 1-D vector, already in Workspace.

This is in an M-file:

function vector = r(i)
vect(i) = q(3*i-2:3*i-1);

If the function is called, for example,

r(2);

Matlab throws an error: "Undefined function or method 'q' for input arguments of type 'double'".

My question is: is there a way to make Matlab take the vector q "for granted" when calling the function rq is already defined so technically it could collected from the base Workspace to use it.

Of course the obvious solution is to add q to the argument list:

function vector = r(i,q)
...

and then call it with

r(2,q)

Eventually I will, but I just want to know if there is something I don't know since this could be a pretty useful feature.

You can use global variables, but you shouldn't . They're inefficient too.

If you for some reason don't just want to pass q in as a second argument, here are two better alternatives.


1. Closure via anonymous function

If your function is simple and can be written on one line you can create an anonymous function after defining your q vector:

q = [1 0 2 4 2 3 4 2 1 0 2];
r = @(i)q(3*i-2:3*i-1);

In this case, the function r is a closure in that it captures the predefined q (note that r in this case is slightly different from that in your question). You can call this now with:

out = r(2)


2. Shared variables via sub-function

A more general option is to use a sub-function inside your main M-file function:

function mainFun
    q = [1 0 2 4 2 3 4 2 1 0 2];
    r(i);

    function vect = r(i)
        vect(i) = q(3*i-2:3*i-1);
    end
end

The vector q is shared between the outer mainFun and the sub-function r . The Matlab Editor should make this clear to you by coloring q differently. More details and examples here .

You can use global variables MATLAB:

1) in the workspace, declare q as global, than set its value

global q;
q = [1 0 2 4 2 3 4 2 1 0 2];

2) in your function, declare q as global and use it:

function vector = r(i)
global q;
vect(i) = q(3*i-2:3*i-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM