Matlab - using undefined function/value within function -


lets start example. define 1-d vector in base workspace:

q = [1 0 2 4 2 3 4 2 1 0 2]; % defined 1-d vector, in workspace. 

this in m-file:

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

if function called, example,

r(2); 

matlab throws error: "undefined function or method 'q' input arguments of type 'double'".

my question is: there way make matlab take vector q "for granted" when calling function rq defined technically collected base workspace use it.

of course obvious solution add q argument list:

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

and call with

r(2,q) 

eventually will, want know if there don't know since pretty useful feature.

you can use global variables, you shouldn't. they're inefficient too.

if reason don't want pass q in second argument, here 2 better alternatives.


1. closure via anonymous function

if function simple , can written on 1 line can create anonymous function after defining q vector:

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

in case, function r closure in captures predefined q (note r in case different in question). can call with:

out = r(2) 


2. shared variables via sub-function

a more general option use sub-function inside 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 shared between outer mainfun , sub-function r. matlab editor should make clear coloring q differently. more details , examples here.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -