Need help with plotting a complicated for loop

1 vue (au cours des 30 derniers jours)
Anthony Schmidt
Anthony Schmidt le 2 Avr 2020
Commenté : David Hill le 3 Avr 2020
Create a function called f that receives an input vector and satisfies the following criteria:
For values of x > 2, f(x) = x^2
For values of x ≤ 2, f(x) = 2x
Plot your results for values of x from –3 to 5. The plot should have a title, and both the x and y axis should be labeled.
I've got my function written and it works, but when I run it, it only plots values for when f(x)=x^2. I know I have a small mistake somewhere, and I'd appreciate if someone could help me out. Here's what I've got so far:
function y=f(x)
for i=x
if i>2
y=x.^2;
elseif i<=2
y=2*x;
end
end
xlabel 'x'
ylabel 'f(x)'
title('Unit Example 4, Problem 6')
plot(x,y,'k*')
end

Réponse acceptée

David Hill
David Hill le 3 Avr 2020
function y=f(x)
for i=x
if i>2
y=x.^2;%you are reassigning y every iteration, your y will be the last one
elseif i<=2
y=2*x;
end
end
xlabel 'x'
ylabel 'f(x)'
title('Unit Exam 4, Problem 6')
plot(x,y,'k*')
end
It is actually much easier without a for-loop.
function y=f(x)
y=zeros(size(x));
y(x>2)=x(x>2).^2;
y(x<=2)=x(x<=2)*2;
xlabel 'x'
ylabel 'f(x)'
title('Unit Exam 4, Problem 6')
plot(x,y,'k*')
end
  2 commentaires
Anthony Schmidt
Anthony Schmidt le 3 Avr 2020
Your funtion works properly and shows the correct values and figure, but question I posted is intending on the user utililzing for/while loops.
David Hill
David Hill le 3 Avr 2020
function y=f(x)
for i=1:length(x)
if x(i)>2
y(i)=x(i)^2;
else
y(i)=2*x(i);
end
end
xlabel 'x'
ylabel 'f(x)'
title('Unit Exam 4, Problem 6')
plot(x,y,'k*')
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur 2-D and 3-D Plots dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by