Graphing changing constants using for loops
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
John D'Errico
2023 年 10 月 28 日
編集済み: John D'Errico
2023 年 10 月 28 日
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 件のコメント
Dyuman Joshi
2023 年 10 月 28 日
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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!