Quick matlab question regarding if statements/for loops

I need to write a code for if x>a then calculate (x-a)^n, if x<=a output 0. I figure my initial issues were that since x can be scalar OR VECTOR then i had to adapt the code for that. I am having issues picking each element from vector x.

My code so far
function y=sfun(x,a,n)
x=input('enter "x" as a vector [a b] or variable: ');
n=input('enter "n" parameter: ');
a=input('enter "a" parameter: ');
for z=x(1:k)
if z>a

I get 27. Which is just the correct answer for 5. When x=0 it should be giving me 0 obviously which it is not.

Added attachment of the piecewise function I am trying to make.


  • I would be happy if anyone knows how to call each cell from a vector of any size that has been input by the user. That is the real issue i am having it seems. so if user inputs for x=[1 2 3 4 5] i want to know how i can take each number and compare it to a=2.

    so if x(1)>a do a function otherwise 0.
    then if x(2)>a do function otherwise 0.
    and keep doing that until the end of the users vector. this part i figured out i believe i can just say k=length(x). x being vector input by user.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion