Graphing changing constants using for loops
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Tashanda Rayne
am 28 Okt. 2023
Kommentiert: Dyuman Joshi
am 28 Okt. 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')
0 Kommentare
Akzeptierte Antwort
John D'Errico
am 28 Okt. 2023
Bearbeitet: John D'Errico
am 28 Okt. 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
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 Kommentar
Dyuman Joshi
am 28 Okt. 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!