3

I am trying to write a function as a script file. And then put the variables in the function to get output as an array.

That's I am able to do:

function trythis
a = [-2 1 7.5]; 
ans = myfunction(a)
end


function y = myfunction(x) 
y = 1./(x.^2 + 1) 
end

However, it shows solution not found. I know how to call the function on the command window but on idea how to make it done all in the script file.

Thanks in advance. Bonnie

Bonnie
  • 55
  • 1
  • 3

1 Answers1

1

You cant declare functions inside script files, each function must be in its own file with the name of the script.

tryThis.m:

function myAns = tryThis
a = [-2 1 7.5]; 
myAns = myFunction(a);

end

myFunction.m:

function y = myFunction( x )

y = 1./(x.^2 + 1) ;

end

now in the main command window you can do this, granted your scripts are in the correct workspace.

>> tryThis

ans =

    0.2000    0.5000    0.0175

Edit: if you want it all in one script:

function myAns = tryThis

a = [-2 1 7.5]; 
myAns = 1./(a.^2 + 1) ;

end

then call it from the command line same way.

brianxautumn
  • 1,162
  • 8
  • 21