0

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.

horchler
  • 18,384
  • 4
  • 37
  • 73
Maverick
  • 420
  • 5
  • 16
  • I'm not sure it is such a useful feature. Requiring the base workspace to have certain variables before your function can work could lead to some confusing errors, and the code could get convoluted, whereas assigning an input to the function is clean and obvious. – David May 12 '15 at 01:02
  • i think your question is somehow similar to my old question here: http://stackoverflow.com/questions/28081836/matlab-access-variable-in-specific-workspace – scmg May 12 '15 at 01:50

2 Answers2

3

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.

Community
  • 1
  • 1
horchler
  • 18,384
  • 4
  • 37
  • 73
0

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);
m.s.
  • 16,063
  • 7
  • 53
  • 88
  • Thanks for tip but I'm going to change q multuple times (these are generalized coordinates) so making them global seems a bit too extreme :D – Maverick May 11 '15 at 23:31