I am trying to run an Octave file which is in the working directory, but I get an error. Octave does not seem to recognize that it should run the file.
unknown@unknown> dir
. ex1data1.txt plotData.m
.. ex1data2.txt submit.m
computeCost.m featureNormalize.m submitWeb.m
computeCostMulti.m gradientDescent.m warmUpExercise.m
ex1.m gradientDescentMulti.m
ex1_multi.m normalEqn.m
unknown@unknown> ex1
error: `ex1' undefined near line 21 column 1
unknown@unknown> ex1.m
error: `ex1' undefined near line 22 column 1
Can anyone advise how I can run the ex1 file?
asked Oct 31, 2013 at 9:11
Timothée HENRYTimothée HENRY
14.1k18 gold badges94 silver badges135 bronze badges
2
This fixed the problem [at least for me, on Windows]:
Entering the following command in Octave:
>addpath(pwd)
before calling the script:
>ex1
There is more info here.
answered Oct 31, 2013 at 12:48
Timothée HENRYTimothée HENRY
14.1k18 gold badges94 silver badges135 bronze badges
Octave (I’m on 4.0.3) will return this error (undefined near line 1 column 1) if you have a capital letter in your path anywhere. For example, if you have a folder on Windows, with the name d:/Myfolder/octave and then you write this:
cd d:/myfolder/octave (note the small «m»)
Then octave will fail.
You have to write exactly the windows path:
cd d:/Myfolder/octave
and octave will be fine
answered Sep 29, 2016 at 16:23
You need to also save the file as «fileName.m»
Octave doesn’t recognize ‘fileName.M’. It has to be a lower-case ‘.m’ extension
answered Mar 25, 2014 at 11:35
BwaxxloBwaxxlo
1,86013 silver badges18 bronze badges
For me, it helped naming file the same as function — it is case sensitive.
answered May 12, 2018 at 16:56
zeroDividerzeroDivider
1,02016 silver badges29 bronze badges
- Your file extension should me .m only sometimes rich text editor or other editors add their own extension behind .m so it becomes like .m.rtf for example.
- In Coursera tutorial the file name is All small case and Function name is camelcased, but that only offered a warning does not throw the error.
-
You should be in the same directory where the .m function file actually exists alternatively as suggested by @tucson above you can use addpath(pwd) to get access from any directory.
answered Jan 11, 2020 at 12:33
VipulVipul
966 bronze badges
Octave reports two kinds of errors for invalid programs.
A parse error occurs if Octave cannot understand something you have typed. For example, if you misspell a keyword,
octave:13> function y = f (x) y = x***2; endfunction
Octave will respond immediately with a message like this:
parse error: syntax error >>> function y = f (x) y = x***2; endfunction ^
For most parse errors, Octave uses a caret (‘^’) to mark the point on the line where it was unable to make sense of your input. In this case, Octave generated an error message because the keyword for exponentiation (**
) was misspelled. It marked the error at the third ‘*’ because the code leading up to this was correct but the final ‘*’ was not understood.
Another class of error message occurs at evaluation time. These errors are called run-time errors, or sometimes evaluation errors, because they occur when your program is being run, or evaluated. For example, if after correcting the mistake in the previous function definition, you type
octave:13> f ()
Octave will respond with
error: `x' undefined near line 1 column 24 error: called from: error: f at line 1, column 22
This error message has several parts, and gives quite a bit of information to help you locate the source of the error. The messages are generated from the point of the innermost error, and provide a traceback of enclosing expressions and function calls.
In the example above, the first line indicates that a variable named ‘x’ was found to be undefined near line 1 and column 24 of some function or expression. For errors occurring within functions, lines are counted from the beginning of the file containing the function definition. For errors occurring outside of an enclosing function, the line number indicates the input line number, which is usually displayed in the primary prompt string.
The second and third lines of the error message indicate that the error occurred within the function f
. If the function f
had been called from within another function, for example, g
, the list of errors would have ended with one more line:
error: g at line 1, column 17
These lists of function calls make it fairly easy to trace the path your program took before the error occurred, and to correct the error before trying again.
© 1996–2018 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/interpreter/Errors.html
Октава сообщает о двух видах ошибок для некорректных программ.
Ошибка синтаксического анализа возникает, если Octave не может понять что-то, что вы набрали. Например, если вы неправильно написали ключевое слово,
octave:13> function z = f (x, y) z = x ||| 2; endfunction
Октава немедленно ответит таким сообщением:
parse error: syntax error >>> function z = f (x, y) z = x ||| y; endfunction ^
Для большинства ошибок разбора Octave использует каретку (‘^‘), чтобы отметить точку на линии, где он не смог понять ваш ввод. В этом случае Octave сгенерировал сообщение об ошибке, потому что ключевое слово для логического или оператора ( ||
) было написано с ошибкой. Он отметил ошибку на третьем ‘|‘ потому что код, ведущий к этому, был правильным, но окончательным ‘|‘ не было понято.
Другой класс сообщений об ошибках возникает во время оценки. Эти ошибки называются ошибками времени выполнения или иногда ошибками оценки , потому что они возникают, когда ваша программа выполняется или оценивается . Например, если после исправления ошибки в предыдущем определении функции вы наберете
octave:13> f ()
Октава ответит
error: `x error: called from: error: f at line 1, column 22
Это сообщение об ошибке состоит из нескольких частей и дает довольно много информации,которая поможет вам найти источник ошибки.Сообщения генерируются из точки самой сокровенной ошибки и обеспечивают трассировку вложенных выражений и вызовов функций.
В приведенном выше примере первая строка указывает,что переменная с именем ‘x‘ оказалось неопределенным рядом со строкой 1 и столбцом 24 какой-то функции или выражения. Для ошибок, возникающих внутри функций, строки отсчитываются от начала файла, содержащего определение функции. Для ошибок, возникающих за пределами объемлющей функции, номер строки указывает номер входной строки, который обычно отображается в основной строке подсказки.
Вторая и третья строки сообщения об ошибке указывают, что ошибка произошла в функции f
. Если бы функция f
была вызвана из другой функции, например g
, список ошибок закончился бы еще одной строкой:
error: g at line 1, column 17
Эти списки вызовов функций позволяют довольно легко проследить путь,пройденный вашей программой до возникновения ошибки,и исправить ошибку перед повторной попыткой.