how to make piece-wise function with if statement ?
Afficher commentaires plus anciens
Please Help me about a great piecewise fun. by matlab 2013a

for k=1,...,n
This is my code.
function p = my_code(x,h)
for k=2:length(x)
if x >= x(k-1) & x <= x(k-1)+h/3
p(k)=(x(1,:)- x(k-1) ).^3;
elseif x>=x(k-1)+h/3 & x<=(x(k-1)+2*h/3)
p(k) =1/2+(3 *( x(1,:)- x(k-1)-h ));
elseif x >=x(k-1)+2*h/3 & x <= x(k)
p(k)=1+(x(1,:)- x(k) ).^2;
elseif x >=x(k) & x <= x(k)+h/3
p(k)=1-(x(1,:)- x(k)-h ).^2;
elseif x >=x(k)+h/3 & x <= x(k)+2*h/3
p(k) =1/2-(3 *( x(1,:)- x(k)-h ));
elseif x >=(x(k)+2*h/3) & x <=x(k+1)
p(k) =-(x(1,:)- x(k+1) ).^3;
else
p(k) = 0;
end
end
end
when run fun. with
h=0.1;
x=0:h:1;
my_code(x,h)
This is what I'm getting:
ans =
0 0 0 0 0 0 0 0 0 0 0
Also, i have problem about k=1,...,n, because i used form k=2:length(m)
Réponse acceptée
Plus de réponses (1)
In theory your code would work, after a few tweaks. In particular you need to read the if documentation, which states that "An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric)." Now have a look at the logical comparison that you perform:
if x >= x(k-1) & ...
you compare a scalar x(k-1) with all of x, which if x is non-scalar will give a non-scalar logical output. Following the description in the if documentation the only time the if will execute is when every element of the expression is non-zero (i.e. true), which most likely for your data is never true. Therefore there will always be some false elements, which means that none of those if or elseif statements will execute, which means only the else will execute and the output will be zeros only.
The fix is to compare scalar values, I guess you intended something like this:
if x(k)>= x(k-1) && ...
But personally I would not use if at all, I would use indexing and vectorize the operations. I would show how, but I do not understand the specification shown. In particular the range is specified from [x_k-1 .... x_k+1], for k = 1:n, which in my limited understanding would means that for adjacent k those ranges overlap, which does not make much sense. Maybe I just don't know that notation.
1 commentaire
work wolf
le 7 Juin 2017
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



