Graphing changing constants using for loops

조회 수: 4 (최근 30일)
Tashanda Rayne
Tashanda Rayne 2023년 10월 28일
댓글: Dyuman Joshi 2023년 10월 28일
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')

채택된 답변

John D'Errico
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
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
Dyuman Joshi
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
str = 1×7 string array
"c = -2" "c = -1" "c = -0.5" "c = 0" "c = 0.5" "c = 1" "c = 2"

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by