(Beginner)Simple for-loop! Help!

8 vues (au cours des 30 derniers jours)
Magnarok
Magnarok le 16 Fév 2017
Commenté : Magnarok le 16 Fév 2017
Hello. I have what I believe is a very simple problem, that I just can't wrap my head around.
I want to plot a sine-curve and a square plot that changes between 0 and 1 as the sinus curve goes between positive and negative value. Here is my code:
x=[0:0.1:3*pi];
y=sin(x);
T = zeros(1,length(x));
for i=1:length(x)
if(sin(i) > 0)
T(i) = 1;
else
T(i) = -1;
end
end
plot(x, y, x, T, 'r');

Réponse acceptée

Geoff Hayes
Geoff Hayes le 16 Fév 2017
Magnarok - rather than conditioning on
sin(i) > 0
use
y(i) > 0
since those are the values of the sine curve. Remember, i is an integer from 1 to the length of your x array, so sin(i) is not what you want to be computing. (I suppose you could do sin(x(i)) > 0 but that seems like extra work when you already have y.)
  1 commentaire
Magnarok
Magnarok le 16 Fév 2017
Thanks alot mate! :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by