MATLAB question ( plot)

  • #1

Homework Statement



Plotting the exponential exp(-cx), 0 ≤ x ≤ 1 with c = 1, 2, 3, 4. Use a for loop.

Homework Equations




The Attempt at a Solution



for c = 1:1:4;
for x = 0:1;
F = exp(-cx);
end
end

plot(x,F)

I'm not really sure where to start..

Help is appreciated.
 

Answers and Replies

  • #2
Choppy
Science Advisor
Education Advisor
Insights Author
4,609
1,728
The way you have it written, F is going to be recalculated for each loop and hold only that single value until the next time it is calculated.
Also while the c variable will increment through integer values as desired, x will also only take the values 0 and 1.

To solve the second problem, try:
for x = 0:0.01:1;

To solve the first you might want to try setting F up as an array, such that F(i,c) = exp(-cx); You would then have to establish independent counter "i" that increments i = i +1 at the beginning of the x loop, and i = 0 at the beginning of the c loop.

With MATLAB you generally don't need to use for loops to solve a problem like this, but perhaps the loop are one point in the exercise.
 
  • #3
So the array x = 0:0.01:1 is actually a loop? I can see that, but how would I nest a counter into that?

Moreover, why would I have to initialise i = 0 in the beginning of the c loop?

Reformed code...

x = 0:0.1:1; <--- Acts as a loop from 0 to 1, 0.1 increments
i = i + 1;

for c = 1:1:4;
i = 0 <---not sure why?
F(i,c) = exp(-c*x);

plot(x,F(c,x))


end

Thanks...
 
  • #4
Choppy
Science Advisor
Education Advisor
Insights Author
4,609
1,728
x = 0:0.1:1; % This line doesn't act as a loop the way you have it now. It makes x an array with values [0.0 0.1... 1.0]. You can keep it a loop if you have to with a "for" statement out front, but if you're going to do that, I would nest it back inside the c loop as you had it before.

You initialize i = 0 for each new value of c. Then increment it for each new value of x. You have to do this before you use it as an index because you can't have an index value of 0.

You'll also have to index x in your F expression if you keep x as a loop, ie. F(i,c) = exp(-c*x(i));

Alternatively if you use x as an array, you don't need the increment counter at all. You would just use the expression:
F(1:length(x),c) = exp(-c.*x);
 
  • #5
Thanks Choppy.

I got the script working.
 

Related Threads on MATLAB question ( plot)

  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
1
Views
868
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
10
Views
10K
  • Last Post
Replies
1
Views
9K
  • Last Post
Replies
6
Views
659
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
1
Views
563
  • Last Post
Replies
5
Views
23K
Top