# MATLAB question ( plot)

## Homework Statement

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

## 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.

Related Engineering and Comp Sci Homework Help News on Phys.org
Choppy
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.

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...

Choppy
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);

Thanks Choppy.

I got the script working.