Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octave calling function from another m file

m file that calls function nraizes(a) from another m file.

clear functions;
clc;
x = input('Insert value for a? ') ;
% call to nraizes()
w = nraizes(x)
clear functions;

nraizes.m file with nraizes() function:

printf("\n\n");
printf("nraizes por André Castro - UAB 901396");
printf("\n");
printf("Usar na próxima prompt: nraizes(valor numérico)");
printf("\n");

function n = nraizes(a)

% limpar a memoria de todas as vars e funções
clear functions;

clc;

% intervalo para x
x = 0:.1:25;
% ambas as funções h(x) e g(x)
h = @(x) cos(x);
g = @(x) exp(a*x)-1;
% traçar linha na origem das abcissas
or = x;
or(:) = 0;
% gráfico
plot(x, [h(x);g(x);or]);
axis([0, 25, -1, 1])
title("h(x),g(x)");
grid on;
printf("Fim do Script");
printf("\n");

% limpar a memoria de todas as vars e funções
clear functions;

endfunction

It always throws the following error:

warning: function 'nraizes' defined within script file '/Users/andrecastro/0_Thawed/1_UAB/1 UCS_INFORMATICA/Computacao Numerica/0 2015-2016_CN/1 Algoritmos_Octave/nraizes.m'
error: invalid use of script /Users/andrecastro/0_Thawed/1_UAB/1 UCS_INFORMATICA/Computacao Numerica/0 2015-2016_CN/1 Algoritmos_Octave/nraizes.m in index expression
error: called from:
error:   /Users/andrecastro/0_Thawed/1_UAB/1 UCS_INFORMATICA/Computacao Numerica/0 2015-2016_CN/1 Algoritmos_Octave/script.m at line 19, column 7

I don't undestand why. Both .m files are in same path.

like image 580
André Castro Avatar asked Sep 27 '22 04:09

André Castro


1 Answers

You have nraizes defined in a file with the same name as the function. You should not do it because now you have both a script and a function, both named nraizes which makes things confusing.

This is what the first warning means:

warning: function 'nraizes' defined within script file '[...]/nraizes.m'

It is warning that the function is on a script with the same name.

You can do it (it's only a warning) but you shouldn't. If you want to do it, you will need to first source the nraizes script and only after that will you have the function available:

nraizes; # source nraizes script
w = nraizes (x); # call nraizes function

That is why you got an error

error: invalid use of script [...]nraizes.m in index expression

because you tried to call a function (or index a variable -- remember that the function is not defined yet so Octave does not know) that does not exist.

However, the printf statements at the top of nraizes.m suggest that you actually want to have it as a function file only. In that case, you should drop those printf's (replace them with comments and they will be displayed when you run help nraizes) so that the first statement is the actual function definition.

like image 123
carandraug Avatar answered Oct 12 '22 23:10

carandraug