Dylan Richards
Dylan Richards

Reputation: 708

How to start a Matlab file without a function being at the top?

Say I have a file StackOverflow that has the following function on line 1:

function [hello] = hai(choice)

end

I then go to the command window and type in StackOverflow and it will run the function. However, I would like to start a timer as soon as the program begins.

That said, I get this error when I try to do so;

Function definitions are not permitted in this context

How can I run this file without the function being at the top of the document?

Upvotes: 1

Views: 49

Answers (1)

tmpearce
tmpearce

Reputation: 12693

From the documentation of creating functions in files:

The definition statement is the first executable line of any function. Function definitions are not valid at the command line or within a script.

In short, you can't have a line of code before the function definition. You have two choices: you can start the timer within the function, or you can start the timer at the command line immediately before calling the function.

If you go with the second option, I suggest using shift-enter after the command to start the timer, before calling your function, so both commands are executed one immediately after the other. Or, you can just use a semi-colon after starting the timer and add the second command on the same line. In either case, both will execute when you hit enter.

Upvotes: 3

Related Questions