just trying to write a simple program to find the gcd of n numbers. I have no clue how to fix this error, i've read all of octaves function documentation and tried to find questions like this ... Just started programming in Octave btw. Here's the code:
function divisor = gcd(x, y)
q=0;
r=0;
l=0;
h=0;
if(x>y)
h=x;
l=y;
elseif(x<y)
h=y;
l=x;
else
h=y;
l=x;
endif
while(r != 0)
q=floor(h/l);
r = h-l*q;
q=h;
r=l;
endwhile
divisor = q;
printf("%d", q);
return;
endfunction
The Error:
error: 'x' undefined near line 6 column 6
error: called from
gcd at line 6 column 3
Thank you :)
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 definer
as 0 in line 3 and don't assign a new value to it later.elseif(x<y)
(line 9) andelse
(line 12) both do exactly the same thing. It would be better to remove theelseif
condition entirely and only haveelse
instead.
I wish you good luck in your studies.
来源:https://stackoverflow.com/questions/44508581/octave-gnu-undefined-variable-x-even-though-its-defined-as-function-input