3

Is there a way in Matlab to store command as string for later use?
For example, if I have

x = 1:10;
plot(x, x);

can I somehow store the 2nd row as str = 'plot(1:10, 1:10)' automatically, so later on I can use the command again simply with eval(str)? Any useful functions for helping me with this task?

p.s. I know it's possible to store the line with str='plot(x,x)', but that's not good enough since it depends on instant values of workspace variable x, which can be changed over time.

3
  • What's your goal? Yes you can simply execute strings using eval. Commented May 4, 2011 at 9:38
  • 1
    eval is almost never the right answer. So I agree with @zellus: what are you trying to do? Commented May 4, 2011 at 9:54
  • @oli, @zellus: my goal here is to perform setstatus commands that were rejected by the server, so I store these commands for later execution. Commented May 4, 2011 at 11:13

1 Answer 1

6

You can try using a closure. In your case that would look like this:

x=1:10;
f = @()plot(x, x);

Now f has everything that is needed to execute the plot (including the information in x) and you can apply it to execute the plot function:

f()
Sign up to request clarification or add additional context in comments.

4 Comments

It should be noted that MATLAB uses the specific term "anonymous function" as opposed to "closure" to refer to these types of functions.
Nitpick: this is not a closure, it is an anonymous function. They behave differently in Matlab. Inline anonymous functions like this get copies of the values in the enclosing workspace's variables it references at the time the handle is constructed. Handles to nested functions are actually closures: they keep "live" references to the variables in the enclosing workspace, and will see later updates to them.
Ha ha! Looks like @gnovice reads his morning StackOverflow about the same time I do.
@Andrew: Yay, Eastern Standard Time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.