I can't define functions in Octave - function

It says that 'x' is not defined and I don't know what to do about it since 'x' is supposed to be an user-defined variable.
I'm new to coding and even newer to Octave and I'm aware that it's an extremely simple, basic question - foolish, even. But even so, if someone could please tell me how to code this, I'd be glad.
function value = sqrmat (x)
% returns true if x is a square matrix and false otherwise
if rows(x)==columns(x)
value=true;
else
value=false;
endif
end

Octave has "script files" and "function files". To create a "script file", use a command (or statement) that has no effect.
Put this command at the top of the file, before all defined functions. Examples:
Declare any number...
In this case, the program assigns this number to the variable "ans".
% script
1;
function value = sqrmat (x)
% returns true if x is a square matrix and false otherwise
if rows(x)==columns(x)
value=true;
else
value=false;
endif
end
A simple message...
It could be a notification, a greeting, and so on.
% script
printf("File accessed\n")

Related

When defining a variable in a julia function, I get an error about an undefined variable on that line

Problem
I'm writing a Julia script, and in the function there is a while loop. Inside the while loop there is a variable. That line is throwing errors about the variable being undefined when in fact that is the very line defining the variable.
The code
The error is on line 65
function cleanTexLoop(fileName::String)
f = open(fileName, "r")
while ! eof(f)
line = readline(f), <-- line 65
#line = sentenceFilter(line)
println(line)
end
close(f)
end
The function opens a file which IS getting passed into a loop. The loop runs until the end of file. While looping the file is read line by line. Each time it is read the line is stored in variable line and the file advances. In the proper version, that one line (66) isn't commented out, however for debugging it is. line is then taken as input into a filter which modifies the line before storing it again as line. The final version of this script will have four filters, but for now, I'd be happy to get this to run with just zero filters.
(Note that a user has kindly pointed out the comma that after hours of looking at the code continued to allude me. I'm waiting for that user to write up an answer)
The error message
cleanTexLoop("test.tex")
ERROR: UndefVarError: line not defined
Stacktrace:
[1] cleanTexLoop(::String) at /home/nero/myScripts/latexCleaner.jl:65
[2] macro expansion at ./REPL.jl:97 [inlined]
[3] (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at > ./event.jl:73
Previous working version
I had previous written another version of this which works in entirety, however I needed to make some substantial changes to its structure in order to better suit future plans. Note that some of the names aren't up to the normal naming convention. Namely, I use "!" when no variables are actually being changed.
function CleanTexLoop(fileName::String,regX::String,sub::String)
f = open(fileName, "r")
while ! eof(f)
println(applySub!(f,regX,sub))
end
close(f)
end
function applySub!(file::IOStream,regX::String,sub::String)
return replace(
readline(file),
Base.Regex(regX),
Base.SubstitutionString(sub)
)
end
A simple loop which demonstrates why this should work
x = 0
while x < 4
y = x
println(y)
x = x+1
end
As expected, this prints zero to one, and is, as far as I can tell, representative of what I am doing. In both cases I am passing some variable into the loop which, through some action, defines another variable inside the loop which is then printed. Why this works, and the other doesn't is beyond me.
What I've seen on Google.
From looking this problem up, it appears as if this problem arrises when defining variables outside of a loop, or similar environment, as a result of them failing to be passed into the environment. However, this isn't what's happening in my case. In my case the variable is being defined for the first time.
As mentioned in the comments, the problem was an errant comma.

Not able to get entire text of current buffer in vim

I am trying to get entire text of current buffer. I believe it is represented by '%' (see answer by SnoringFrog at https://vi.stackexchange.com/questions/2319/is-there-a-text-object-for-the-entire-buffer). However, following function gives an error:
function Check ()
echo %
endfunction
I call it with following command:
:call Check()
The error is:
Error detected while processing function Check:
line 1:
E15: Invalid expression: %
E15: Invalid expression: %
Where is the problem and how can it be solved?
Depending on the context, % can be a shortcut for the 1,$ range or a placeholder for the filename associated with the current buffer.
In the first case (the one in your link), it's not meant to be echoed at all which would be completely pointless.
In the second case, it needs to be expanded with expand('%') if you want to use it in a function.
Anyway, none of that matters because % is not what you want at all. What you want is :help getline():
function Check ()
echo getline(1,'$')
endfunction

What is this line getting from a different file (TCL)?

I am including the relevant code below, and I can explain what I know it is doing up to this point:
proc rshm {where {i 0}} {
global ob
set what "???"
set ob(last_rshm_failed) "yes"
if {![info exists ob(shm)]} {
return "0.0"
}
if {[info exists ob(shm_puts_exist_in_progress)]} {
return "0.0"
}
shm_puts "g $where $i"
gets $ob(shm) istr
set what [lindex $istr 0]
set ob(last_rshm_failed) "no"
if {[string equal $what "?"]} {
set ob(last_rshm_failed) "yes"
puts stderr $istr
return "0.0"
}
set what [lindex $istr 3]
return $what
}
From looking at the rest of the program, I have concluded that the first two if statements are checking for errors elsewhere and are designed to terminate the procedure if the errors trigger.
Elsewhere in the program, the place (of interest) that the function gets called is in the form: rshm ft_xdev
Using print statements, I found that ft_xdev passes into the procedure as shm_puts "g ft_xdev 0".
The line that is throwing me off is the line: gets $ob(shm) istr
The call to $ob(shm) is another file (originally a binary program, but the readable version is in C...), but upon looking at this file, there is no reference to anything called "istr".
Would someone mind helping me out with what this line is getting from the other file? If needed, I can provide more code from the program.
The code:
gets $ob(shm) istr
will pass the contents of the ob(shm) variable (which should be a channel handle that is at least open for reading) and the string istr (which is used to name a variable in this case) into the gets command. The istr will be a local variable in this case because it hasn't been explicitly stated to be otherwise.
The gets command, when given two arguments, will read a line of text from the channel (first arg) and write that line of text to the variable (second arg). It then yields as result the number of characters read or -1 if there was a recoverable error condition such as end-of-file. You're ignoring the result. (Critical errors would become exceptions.) This is all documented on the manual page for gets.
tl;dr: Reads a line of text from the $ob(shm) channel and stores it in istr.
This procedure will return the 3rd index of $istr ([lindex $istr 3]) if its not empty or does not fail on the prior checks.
The contents of $istr are obtained from grabbing the next line of the open file channel $ob(shm) (if the channel is already open and $ob(shm_puts_exist_in_progress) does not exist).
If shm_puts "g $where $i" impacts the $ob in any way, it would be important to include the procedure shm_puts since it may impact $istr, but I suspect the contents of shm_puts are not relevant to $istr.
Finally if $istr starts with a ? then it aborts this procedure displaying the contents of $istr to stderr. That is, if a line of the file starts with ?, then the procedure aborts.
All procedure aborts (ie IF checks) do not retain the contents of $istr, since its a local variable not a global one, so checking the contents of $istr must be done within this procedure and after the gets command.

FORTRAN 95 To main PROGRAMS error when using function and Expected formal argument list in function

My code works except for when I am trying to use a function to calculate the average of a set of values from an array. I omitted the large part of my program because without doing these steps everything runs fine. Thank you!
Inside my main program I have
averagecalc=average(array(stepsize),stepsize)
WRITE(*,*) averagecalc
Out of my main program I have
FUNCTION average(array(),stepsize)
REAL,INTENT(IN),DIMENSION(stepsize)::array
INTEGER,INTENT(IN)::stepsize
average=SUM(array(stepsize))/stepsize
END FUNCTION
My full program is
PROGRAM subroutines
IMPLICIT NONE
!variables
INTEGER:: i,stepsize,j,counts
CHARACTER:: choice
REAL,EXTERNAL:: functions,average
REAL:: a,function1,function2,function3,x,upperbound,lowerbound,averages,sums,averagecalc
REAL,ALLOCATABLE::array(:)
!formats
101 FORMAT(A) !single text element only
102 FORMAT() ! <description>
!-------Variable Definitions-------!
! INTEGER:
! i: used as a counter
! stepsize: the number of steps the user inputs
! j: used as a counter
! counts: used to keep track of steps
!
! CHARACTER:
! choice:
! REAL,EXTERNAL:
! functions:
! average:
! REAL:
!
!
!
!
!
!
!
!
!
!
!----------------------------------!
!<Begin Coding Here>
!Taking in information on which equation and bounds and stepsize
CALL section1(lowerbound,upperbound,stepsize,choice)
!Calculating equations based on choices and allocating array,writing out array
ALLOCATE(array(stepsize))
x=lowerbound
counts=0
WRITE(*,101) ' |----------------------|'
WRITE(*,101) ' |Step | x | f(x)|'
WRITE(*,101) ' |----------------------|'
DO i=1,stepsize
IF(choice.EQ.'A') THEN
array(i)=function1(x)
ELSE IF(choice.EQ.'B') THEN
array(i)=function2(x)
ELSE IF(choice.EQ.'C') THEN
array(i)=function3(x)
END IF
counts=counts+1
WRITE(*,'(I10,F10.3,F10.3)') counts,x,array(i)
x=x+(upperbound-lowerbound)/stepsize
END DO
!Writing the averages
averagecalc=average(array(stepsize),stepsize)
WRITE(*,*) averagecalc
END PROGRAM subroutines
!------------------------------------------------SECTION 1-------------------------------------------------
SUBROUTINE section1(lowerbound,upperbound,stepsize,choice)
IMPLICIT NONE
REAL,INTENT(OUT)::lowerbound,upperbound
INTEGER,INTENT(OUT):: stepsize
CHARACTER,INTENT(OUT):: choice
101 FORMAT(A) !single text element only
102 FORMAT() ! <description>
WRITE(*,101) 'Please choose one of the following choices with a capital letter;'
WRITE(*,*)
WRITE(*,101) 'A) f(x)=x^2+2*x+4'
WRITE(*,*)
WRITE(*,101) 'B) f(x)=|x+4|'
WRITE(*,*)
WRITE(*,101) 'C) f(x)=sin(x)+42'
READ(*,*) choice
IF(choice.EQ.'A') THEN
WRITE(*,*)
ELSE IF(choice.EQ.'B') THEN
WRITE(*,*)
ELSE IF(choice.EQ.'C') THEN
WRITE(*,*)
ELSE
STOP 'Please enter either A, B, or C'
END IF
WRITE(*,101) 'Please enter a lower bound'
READ(*,*) lowerbound
WRITE(*,101) 'Please enter a upper bound'
READ(*,*) upperbound
WRITE(*,101) 'Please enter a step size'
READ(*,*) stepsize
END SUBROUTINE section1
!-------------------------------------------------------functions------------------------------------------
FUNCTION function1(x)
REAL,INTENT(IN)::x
function1=((x**2)+(2*x)+4)
END FUNCTION
FUNCTION function2(x)
REAL,INTENT(IN)::x
function2=ABS(x+4)
END FUNCTION
FUNCTION function3(x)
REAL,INTENT(IN)::x
function3=sin(x)+42
END FUNCTION
!---------------------------------------average value--------------------------
FUNCTION average(array(),stepsize)
REAL,INTENT(IN),DIMENSION(stepsize)::array
INTEGER,INTENT(IN)::stepsize
average=SUM(array(stepsize))/stepsize
END FUNCTION
There is at least one syntactic error in your code which will prevent compilation, in this line
FUNCTION average(array(),stepsize)
where the empty parentheses after array are not permitted. Personally I wouldn't delete them, I'd rewrite the function somewhat like
real function average(array)
real, dimension(:), intent(in) :: average
average = sum(array)/size(array)
end function average
Passing the size of the array as a separate argument is unnecessary in modern Fortran, and rather suggests, as your previous question did, that you are sending your questions through a wormhole from about 1979.
As you've constructed your source file the compiler can't check that the arguments passed to your procedures match the procedure definitions. Either follow the advice you have already had to place them into a module and use-associate them, or:
move the line end program subroutines to the end of the source file; AND
in the location you move that line from insert the line contains
These two steps will allow the compiler to check procedure interfaces.
Finally, you have two semantic errors in your program, one serious, one less so.
One, you have a variable named stepsize whose use and description make it clear that this is actually a number of steps. You even prompt the user to enter a step size but treat the response as a number of steps. That's just wrong.
Two, you have a program named subroutines. What ?!
Finally, and I mean it this time, if you ask further questions here on SO I suggest:
that you actually ask a question, your posting above doesn't;
if you have a question about code which won't compile then report the error messages your compiler raises;
while whitespace is, in general, a good thing, lots of empty lines in snippets posted on SO just make your readers task more laborious; I don't see anywhere in this question where multiple blank lines couldn't be replaced by a single blank line without improving your post's readability.

Is there something equivalent to C's #include in Octave?

Suppose that I have 2 scripts:
magic_function.m:
function retval = magic(x)
retval = 12345678;
endfunction
other_script.m
#some code
X = magic(17)
What should I add to other_script.m in order to make function "magic" visible?
Judging by the documentation of Functions and Script Files, it should be sufficient to put the function in a file named magic.m in a directory specified in LOADPATH.
When Octave encounters an identifier that is undefined, it first looks
for variables or functions that are already compiled and currently
listed in its symbol table. If it fails to find a definition there, it
searches the list of directories specified by the built-in variable
LOADPATH for files ending in `.m' that have the same base name as the
undefined identifier.(4) Once Octave finds a file with a name that matches, the contents of the file are read. If it defines a single
function, it is compiled and executed.