I try to read a matrix from a file. The code is very simple
function [mat] = read(file)
mat = load(file_points)
But when I try to run it
read('file')
mat =
scalar structure containing the fields:
mat =
3 4 6
3 5 1
it shows the matrix,
but when I run this command…
>>mat(1,1)
error: ‘points’ undefined near line 1 column 1
asked Mar 18, 2019 at 20:21
alexandru99jalexandru99j
31 gold badge1 silver badge4 bronze badges
4
From Octave Forge about load()
If invoked with a single output argument, Octave returns data instead of inserting variables in the symbol table. If the data file contains only numbers (TAB- or space-delimited columns), a matrix of values is returned. Otherwise, load returns a structure with members corresponding to the names of the variables in the file.
According to above, variable points is a (scalar) structure.
However, if you use the_matrix_you_want = points.points;
you would retrieve matrix.
answered Mar 19, 2019 at 6:23
RishRish
4044 silver badges7 bronze badges
0
Я пытаюсь запустить Октавный файл, который находится в рабочем каталоге, но я получаю ошибку. Octave, похоже, не признает, что он должен запустить файл.
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
может ли кто-нибудь посоветовать, как я могу запустить файл ex1?
4 ответов
это исправило проблему [по крайней мере для меня, на Windows]:
ввод следующей команды в Октаве:
>addpath(pwd)
перед вызовом скрипта:
>ex1
there is more info здесь.
Октава (я на 4.0.3) вернет эту ошибку (не определено рядом с строкой 1 столбец 1), Если у вас есть заглавная буква на вашем пути в любом месте. Например, если у вас есть папка в Windows с именем d:/Myfolder/octave а потом пишешь:
cd d:/myfolder/octave (обратите внимание на маленькую «м»)
тогда Октава потерпит неудачу.
вы должны написать точно путь windows:
компакт-диск d:/Myfolder/octave
и Октава будет в порядке
вам также необходимо сохранить файл как » fileName.м»
Октава не распознает ‘fileName.М. Она должна быть строчной».расширение м’
для меня это помогло назвать файл так же, как функция-он чувствителен к регистру.
how i could run SDF command in octave when i get this error:
so i have seen this GitHub related project (octave-networks-toolbox) and into is there was SDF, so i tried to install it by this command:
so@so-notebook:~$ sudo aptitude install octave-networks-toolbox
[sudo] password for so:
Couldn't find any package whose name or description matched "octave-networks-toolbox"
Unable to apply some actions, aborting
Thanks for your attention.
asked Dec 29, 2019 at 11:32
2
There is no octave-networks-toolbox
package in the Ubuntu repositories, so you can’t install it using APT.
The octave-networks-toolbox
project is a set of m-files.
So you need to download it, extract and run from Octave:
cd ~/Downloads
wget https://codeload.github.com/aeolianine/octave-networks-toolbox/zip/master -O octave-networks-toolbox-master.zip
unzip octave-networks-toolbox-master.zip
cd octave-networks-toolbox-master
octave testAllFunctions.m
As for any other MATLAB/Octave code, you can add it to the path
variable with addpath
.
answered Dec 29, 2019 at 11:58
N0rbertN0rbert
96.1k33 gold badges232 silver badges418 bronze badges
2
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 badges92 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 badges92 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
how i could run SDF command in octave when i get this error:
so i have seen this GitHub related project (octave-networks-toolbox) and into is there was SDF, so i tried to install it by this command:
so@so-notebook:~$ sudo aptitude install octave-networks-toolbox
[sudo] password for so:
Couldn't find any package whose name or description matched "octave-networks-toolbox"
Unable to apply some actions, aborting
Thanks for your attention.
asked Dec 29, 2019 at 11:32
2
There is no octave-networks-toolbox
package in the Ubuntu repositories, so you can’t install it using APT.
The octave-networks-toolbox
project is a set of m-files.
So you need to download it, extract and run from Octave:
cd ~/Downloads
wget https://codeload.github.com/aeolianine/octave-networks-toolbox/zip/master -O octave-networks-toolbox-master.zip
unzip octave-networks-toolbox-master.zip
cd octave-networks-toolbox-master
octave testAllFunctions.m
As for any other MATLAB/Octave code, you can add it to the path
variable with addpath
.
answered Dec 29, 2019 at 11:58
N0rbertN0rbert
94.2k30 gold badges223 silver badges407 bronze badges
2
Я пытаюсь запустить Октавный файл, который находится в рабочем каталоге, но я получаю ошибку. Octave, похоже, не признает, что он должен запустить файл.
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
может ли кто-нибудь посоветовать, как я могу запустить файл ex1?
4 ответов
это исправило проблему [по крайней мере для меня, на Windows]:
ввод следующей команды в Октаве:
>addpath(pwd)
перед вызовом скрипта:
>ex1
there is more info здесь.
Октава (я на 4.0.3) вернет эту ошибку (не определено рядом с строкой 1 столбец 1), Если у вас есть заглавная буква на вашем пути в любом месте. Например, если у вас есть папка в Windows с именем d:/Myfolder/octave а потом пишешь:
cd d:/myfolder/octave (обратите внимание на маленькую «м»)
тогда Октава потерпит неудачу.
вы должны написать точно путь windows:
компакт-диск d:/Myfolder/octave
и Октава будет в порядке
вам также необходимо сохранить файл как » fileName.м»
Октава не распознает ‘fileName.М. Она должна быть строчной».расширение м’
для меня это помогло назвать файл так же, как функция-он чувствителен к регистру.
I try to read a matrix from a file. The code is very simple
function [mat] = read(file)
mat = load(file_points)
But when I try to run it
read('file')
mat =
scalar structure containing the fields:
mat =
3 4 6
3 5 1
it shows the matrix,
but when I run this command…
>>mat(1,1)
error: ‘points’ undefined near line 1 column 1
asked Mar 18, 2019 at 20:21
alexandru99jalexandru99j
31 gold badge1 silver badge4 bronze badges
4
From Octave Forge about load()
If invoked with a single output argument, Octave returns data instead of inserting variables in the symbol table. If the data file contains only numbers (TAB- or space-delimited columns), a matrix of values is returned. Otherwise, load returns a structure with members corresponding to the names of the variables in the file.
According to above, variable points is a (scalar) structure.
However, if you use the_matrix_you_want = points.points;
you would retrieve matrix.
answered Mar 19, 2019 at 6:23
RishRish
3943 silver badges7 bronze badges
0
I try to read a matrix from a file. The code is very simple
function [mat] = read(file)
mat = load(file_points)
But when I try to run it
read('file')
mat =
scalar structure containing the fields:
mat =
3 4 6
3 5 1
it shows the matrix,
but when I run this command…
>>mat(1,1)
error: ‘points’ undefined near line 1 column 1
asked Mar 18, 2019 at 20:21
alexandru99jalexandru99j
31 gold badge1 silver badge4 bronze badges
4
From Octave Forge about load()
If invoked with a single output argument, Octave returns data instead of inserting variables in the symbol table. If the data file contains only numbers (TAB- or space-delimited columns), a matrix of values is returned. Otherwise, load returns a structure with members corresponding to the names of the variables in the file.
According to above, variable points is a (scalar) structure.
However, if you use the_matrix_you_want = points.points;
you would retrieve matrix.
answered Mar 19, 2019 at 6:23
RishRish
3943 silver badges7 bronze badges
0
Октава сообщает о двух видах ошибок для некорректных программ.
Ошибка синтаксического анализа возникает, если 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
Эти списки вызовов функций позволяют довольно легко проследить путь,пройденный вашей программой до возникновения ошибки,и исправить ошибку перед повторной попыткой.
I try to read a matrix from a file. The code is very simple
function [mat] = read(file)
mat = load(file_points)
But when I try to run it
read('file')
mat =
scalar structure containing the fields:
mat =
3 4 6
3 5 1
it shows the matrix,
but when I run this command…
>>mat(1,1)
error: ‘points’ undefined near line 1 column 1
points=read_input_data('cls/cluster_1.points')
. Also add a semicolon at the end of your statements if you don’t what Octave to display the resulting matrices.
– Cris Luengo
Your function declaration is read but you call read_input_data, please fix this error
– Andy
«I think that are comments, so it shouldn’t influence too much». Actually, those comments in the header are what make this text file a .mat file that you can read with load
. Try removing them and see what happens.
– beaker
1 Answers
From Octave Forge about load()
If invoked with a single output argument, Octave returns data instead of inserting variables in the symbol table. If the data file contains only numbers (TAB- or space-delimited columns), a matrix of values is returned. Otherwise, load returns a structure with members corresponding to the names of the variables in the file.
According to above, variable points is a (scalar) structure.
However, if you use the_matrix_you_want = points.points;
you would retrieve matrix.
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
Эти списки вызовов функций позволяют довольно легко проследить путь,пройденный вашей программой до возникновения ошибки,и исправить ошибку перед повторной попыткой.
0 / 0 / 0
Регистрация: 19.12.2020
Сообщений: 25
1
При попытке создать график что-то идёт не так
24.01.2021, 05:47. Показов 761. Ответов 8
Помогите пожалуйста построить график функции: Определить функцию f(x), вычислить ее значение при x = 2,9. Построить таблицу значений функции для x[2; 12] с шагом 1. Построить график функции. Каждый раз когда я разными способами пыталась что-то сделать, он пишет разного рода ошибки.
Matlab M | ||
|
пишет вот такую ошибку:error: ‘ploat’ undefined near line 1 column 1.
Пыталась вот так сделать ещё:
Matlab M | ||
|
тут вообще в самом начале такую ошибку выдаёт:error: for A^b, A must be a square matrix. Use .^ for elementwise power.
я уже честно говоря не знаю что делать, как только я с условиями и кодом не экспериментировала, ничего не получается, изучаю совсем немного по времени, но я пытаюсь что-то сделать, осталось последнее задание на графики и у меня вообще ничего не выходит с ними. Вот условие:Определить функцию f(x), вычислить ее значение при x = 2,9. Построить таблицу значений функции для x[2; 12] с шагом 1. Построить график функции.
Само задание(7 вариант) :
0
ProgrammerAH
Programmer Guide, Tips and Tutorial
. M file name should also be capitalized: squarethisnumber m
Question 2:
parse error near line 1 of file C:UsersasussquareThisNumber. m
syntax error
>>> {rtf1ansiansicpg936deff0nouicompat{fonttbl{f0fnilfcharset134 ’cb’ce’cc’e5;}}
Solution: the WordPad program (nodepad) opens the file and finds many redundant characters. Delete them and add endfunction at the end.
Read More:
jovyan@jupyter-jasonmoore-40ucdavis-2eedu:~$ octave-cli -v
GNU Octave, version 4.2.1
Copyright (C) 2017 John W. Eaton and others.
This is free software; see the source code for copying conditions.
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.
Octave was configured for "x86_64-pc-linux-gnu".
Additional information about Octave is available at http://www.octave.org.
Please contribute if you find this software useful.
For more information, visit http://www.octave.org/get-involved.html
Read http://www.octave.org/bugs.html to learn how to submit bug reports.
jovyan@jupyter-jasonmoore-40ucdavis-2eedu:~$ octave-cli
GNU Octave, version 4.2.1
Copyright (C) 2017 John W. Eaton and others.
This is free software; see the source code for copying conditions.
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. For details, type 'warranty'.
Octave was configured for "x86_64-pc-linux-gnu".
Additional information about Octave is available at http://www.octave.org.
Please contribute if you find this software useful.
For more information, visit http://www.octave.org/get-involved.html
Read http://www.octave.org/bugs.html to learn how to submit bug reports.
For information about changes from previous versions, type 'news'.