Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is that the variable <code>persons</code> isn't accessible inside the function <code>process_store</code>. In Matlab (and most other programming languages) functions can't access variables defined in their calling functions. To understand this better, I recommend having a read of the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Scope_%28computer_science%29" rel="nofollow">levels of scope</a>.</p> <p>You essentially have two options here:</p> <ol> <li><p>Make <code>persons</code> a global variable, both in your workspace and in the function <code>process_store</code>, by using the declaration <code>global persons</code>. I wouldn't recommend this.</p></li> <li><p>Use the function <code>evalin</code> to allow <code>process_store</code> to access variables in its parent workspace.</p></li> </ol> <p>I'd go with option 2 if I were you. It's a little tricky, so let me explain how it works. Let's create a variable <code>persons</code> in the global workspace.</p> <pre><code>&gt;&gt; persons = {'John', 'Jack', 'Jill'}; </code></pre> <p>Now say we have the following function</p> <pre><code>function example() x = input('Give me a variable name: '); disp(x) end </code></pre> <p>What happens if we try to use it?</p> <pre><code>&gt;&gt; example() Give me a variable name: persons Error using input Undefined function of variable 'persons' Error in example (line 2) x = input('Give me a variable name: '); </code></pre> <p>Oh dear. That's because the function <code>example</code> doesn't have access to the global workspace, which is where <code>persons</code> is defined. But instead, we can store the name of the variable we want to access, and then check out its value in the global workspace by using <code>evalin</code>, like this</p> <pre><code>function example() s = input('Give me a variable name: ', 's'); x = evalin('caller', s); disp(x) end </code></pre> <p>Now if we use it:</p> <pre><code>&gt;&gt; example() Give me a variable name: persons 'John' 'Jack' 'Jill' </code></pre> <p>It works as we expected! Great!</p> <h3>Massive disclaimer</h3> <p>There is almost never a good reason to use functions like <code>evalin</code> (or <code>eval</code>, or <code>assignin</code> or any other function that messes around executing strings as code). There's almost certainly a better way of doing what you want to do. But without knowing what it is you're trying to do, it's hard to give you better advice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload