Graphing changing constants using for loops

4 views (last 30 days)
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')

Accepted Answer

John D'Errico
John D'Errico on 28 Oct 2023
Edited: John D'Errico on 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 Comment
Dyuman Joshi
Dyuman Joshi on 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"

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!