Effacer les filtres
Effacer les filtres

Graphing changing constants using for loops

1 vue (au cours des 30 derniers jours)
Tashanda Rayne
Tashanda Rayne le 28 Oct 2023
Commenté : Dyuman Joshi le 28 Oct 2023
Can someone please help me understand why its not graphing all the constants properly?
close all
x = -50:100:50;
U = -10:1:10;
c = [-2, -1, -0.5, 0, 0.5, 1, 2];
for i = 1:1:7
U = c(i).*exp(-3*tan(x))+(1/3);
plot(x,U)
hold on
end
xlabel('x')
ylabel('y')
title('Homework 1.4 #6')
legend('c = -2', 'c = -1', 'c = -0.5', 'c = 0', 'c = 0.5', 'c = 1', ' c = 2', 'location' , 'best')

Réponse acceptée

John D'Errico
John D'Errico le 28 Oct 2023
Modifié(e) : John D'Errico le 28 Oct 2023
Why do you think it is not? Ok, there are multiple problems in your code.
First, maybe I should ask what you think this line does? I'll remove the semi-colon, just so you can see.
x = -50:100:50
x = 1×2
-50 50
Do you understand that creates a vector of length ONLY 2? Maybe you think it should generate 100 steps between those limits. NO.
You might want to learn what the second (middle) argument for colon does. Or, learn how to use linspace.
As well, why did you define U before the loop? That line is just a waste of CPU cycles, since then you directly overwrite U inside the loop.
I'll change a few things...
x = linspace(-10,10,1000); % linspace instead of colon, so many more points, more finely spaced
% as well, I reduced the domain for x, so there are fewer cycles chown.
% dropped U
c = [-2, -1, -0.5, 0, 0.5, 1, 2];
for i = 1:numel(c) % don't hard code the length of the loop, but base it on the length of c
U = c(i).*exp(-3*tan(x))+(1/3);
plot(x,U)
hold on
end
xlabel('x')
ylabel('y')
ylim([-10,10]) % limits the range of y to make the interesting part visible
title('Homework 1.4 #6')
legend('c = -2', 'c = -1', 'c = -0.5', 'c = 0', 'c = 0.5', 'c = 1', ' c = 2', 'location' , 'best')
  1 commentaire
Dyuman Joshi
Dyuman Joshi le 28 Oct 2023
Just to add to John's answer, you can create the strings like this
c = [-2, -1, -0.5, 0, 0.5, 1, 2];
str = "c = " + c
str = 1×7 string array
"c = -2" "c = -1" "c = -0.5" "c = 0" "c = 0.5" "c = 1" "c = 2"

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by