Having Trouble with My Input Argument!

function output=myfun(x)
x=3
if x<-2
output=-x^2;
elseif (-2<=x)&&(x<0)
output=-2*x;
elseif (0<=x)&& (x<=2)
output=2*x;
elseif x>2
output=x^2;
end

8 Comments

how do you call this function?
the function is called myfun.m
That did not answer here question. Again, how do you call it and what do you pass in for x? For example
>> myfun(50)
Plus, you need to split up -2<=x<0 into two tests, like you did with the elseif right after that one.
Well the problem statement doesn't give me anything to pass in for x.
It says "create a function called myfun with input x, that satisfies the following criteria" Then proceeds to list the 4 conditions i put into my code. "For values of x<-2, f(x) = -x^2..." and so on
But clearly you must pass something in to use the function as you have it written, even if your "problem statement" doesn't explicitly state so.
@ James
If i want to pass a matrix such as x=(-10:10) it will just give me an error saying that the program expects a scalar quantity, it wont even allow me to run it.
Even though it doesn't explicitly tell you to pass in anything, it's pretty much implicit that if you want to test your function to see if it works, you must pass in something, like Azzi's showing you, unless you just want to turn in your assignment untested (not a wise idea).
I edited my question and code.
If i do the code as shown, i get the exact answer i'm looking for when i run it. My problem is that i want my input to deal with all possible x values, how exactly do i do this? I shouldn't have to go to my function and edit my x value each time i want to test it, right?

Sign in to comment.

 Accepted Answer

function output=myfun(x)
if x<-2
output=-x^2;
elseif -2<=x && x<0
output=-2*x;
elseif 0<=x && x<=2
output=2*x;
elseif x>2
output=x^2;
end

4 Comments

Yes sorry, that is what my initial function looks like, i copied it wrong in my question. Still the same error
Your file is a function saved as myfun you can't run it as a script by clicking the icon run . You need to call your function in another script or in Matlab command windows:
x=10 % for example
y=myfun(x)
I edited my question and code.
If i do the code as shown, i get the exact answer i'm looking for when i run it. My problem is that i want my input to deal with all possible x values, how exactly do i do this? I shouldn't have to go to my function and edit my x value each time i want to test it, right?
What x=3 is doing inside your function, you have first, to understand how functions work. When you call your function
y=myfun(3),
the function will assign 3 to the argument x, and run your code for this value, if you want to test another value, just write
y=myfun(-1)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!