Undefined near line 1 column 1 octave ошибка

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

alexandru99j's user avatar

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

Rish's user avatar

RishRish

4044 silver badges7 bronze badges

0

This code will read the entire file into memory and remove all whitespace characters (newlines and spaces) from the end of each line:

with open(filename) as file:
    lines = file.readlines()
    lines = [line.rstrip() for line in lines]

If you’re working with a large file, then you should instead read and process it line-by-line:

with open(filename) as file:
    for line in file:
        print(line.rstrip())

In Python 3.8 and up you can use a while loop with the walrus operator like so:

with open(filename) as file:
    while (line := file.readline().rstrip()):
        print(line)

Depending on what you plan to do with your file and how it was encoded, you may also want to manually set the access mode and character encoding:

with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline().rstrip()):
        print(line)

This should work:

#!/usr/bin/octave -qf

arg_list = argv ();
filename = arg_list{1};
load("-ascii",filename);

when you wrote the line load filename you indicated to the load function to load the file name «filename». That is to say, you did the thing that is equivalent to load('filename');.

In both MATLAB and Octave, a function «foo» followed by a space then the word «bar» indicates that bar is to be submitted as a string to foo. This is true even if bar is a defined variable in your workspace.

how i could run SDF command in octave when i get this error:

enter image description here

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

Soheil Paper's user avatar

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

N0rbert's user avatar

N0rbertN0rbert

97.3k34 gold badges239 silver badges424 bronze badges

2

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

As an AI language model, I don’t think you can save files in Rich Text Format (.rtf) format from WordPad. I assume you meant to say that you saved the function in a .txt file.

To solve the error, it is important to ensure that the path to the function file is correct. In the example given, the path provided in the code has a duplication. The correct code to change the directory to the Desktop should be:

cd 'C:\Users\username\Desktop';

Once the directory is changed, you can call the function by its name as follows:

testFunc(4);

However, the function ‘testFunc’ needs to be saved with a “.m” extension, which is the extension used for Octave script files. Therefore, save the function in a text file with a “.m” extension, and call the file name with its extension as follows:

testFunc.m

You can confirm that the function is in the current workspace by using the “whos” command or typing the function’s name at the octave prompt.

Once you have solved these issues, your code should run successfully.

Я пытаюсь запустить Октавный файл, который находится в рабочем каталоге, но я получаю ошибку. 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.М. Она должна быть строчной».расширение м’


для меня это помогло назвать файл так же, как функция-он чувствителен к регистру.


Понравилась статья? Поделить с друзьями:
  • Undeclared first use in this function ошибка c
  • Unixfit ошибка e7 беговая дорожка
  • Und ошибка на машинке haier
  • Unityplayer dll ошибка что делать
  • Uncserver exe ошибка приложения