Your code is a function definition. Your function is called gcd
.
You have to save your code in a file called gcd.m
and then create a new file so that you can call that function from it.
In the same directory you have saved gcd.m
, create a file (for example: gcdtest.m
) and put the following code in it:
test = gcd(40, 50)
Then save and run this file. If the output doesn't work as expected, restarting Octave should fix it.
The numbers I've chosen are only an example.
Explanation:
If all you have is the function definition file (i.e. gcd.m
), when you hit "Save and run", Octave will itself call your function, but it's not clever enough and won't use any parameters in doing so. That's why you get an "undefined variable" error. That would be similar to you having only test = gcd()
in your test file.
If, however, you call the function with the arguments, they will initialize the variables x
and y
correctly and your code will work.
You can also simply call gcd(40, 50)
from the Octave command line, for testing purposes.
The following are links to the Octave documentation regarding functions and function files (I know you said you read them, but newcomers might not have):
https://www.gnu.org/software/octave/doc/interpreter/Defining-Functions.html
https://www.gnu.org/software/octave/doc/interpreter/Function-Files.html
Now, I noticed a couple of issues in your code:
while(r != 0)
on line 16 - this won't run, not even once, since you define r
as 0 in line 3 and don't assign a new value to it later.
elseif(x<y)
(line 9) and else
(line 12) both do exactly the same thing. It would be better to remove the elseif
condition entirely and only have else
instead.