wx13
wx13

Reputation: 85

How to execute octave code line-by-line

If I start an octave interactive shell, I can type:

octave:1> function y = foo(x)
> y = x + 2;
> endfunction
octave:2> foo(7)
ans = 9

The interpreter knows to wait for the rest of the function definition.

However, if I do

octave:1> eval("function y = foo(x)");
octave:2> eval("y = x + 2;");
octave:3> eval("endfunction");

it evaluates each line as if it were alone. So it defines a function foo which does nothing, and gives errors for the second two lines.

Is there any way to get eval to operate the same as the interpreter? Ultimately, I would like to create an octave script which executes another script, but is able to do other things in between. Is there any way to tell eval to wait for the rest of the command (the way the interactive environment does)? Alternatively, is there a way to feed commands to the interactive interpreter programmatically?

Thank you.

Upvotes: 0

Views: 1743

Answers (1)

carandraug
carandraug

Reputation: 13081

To answer your exact question, I see two immediate ways to do it:

octave> eval ("function y = foo(x) ...
y = x + 2; ...
endfunction")
octave> eval ("function y = foo(x)\n y = x + 2;\n endfunction")

The thing is that you can't split each line in multiple evals, it doesn't make sense. You want to pass a single string with all of the code. Also, you can use the source function to execute code from other files.

Without knowing all the details of what're you're trying to do, I'm guessing you could have your code use input to wait for input from the other code. Or just turn your other script into functions, and call them from your main script.

Upvotes: 1

Related Questions