rag123
rag123

Reputation: 3

How do I plot inside a for loop? Matlab

I'm trying to plot a straight line from a point in x to different values of t, thereby making a line in a for loop. But I see no lines generated in my figure in MATLAB

Following is my code:

 t=linspace(0,8,11)
xs=(1.+t).^0.5
x0=xs./(1.+t)
m=size(t)
n=max(m)
hold on
for k=1:n
plot(x0(k),t(1:k),'-')
 hold on
end

Thanks

Upvotes: 0

Views: 1299

Answers (2)

Matt Popovich
Matt Popovich

Reputation: 240

You do not need the loop to perform the plot.

plot(x0,t,'-')

Will work just fine! Unless you were attempting to plot points...use scatter() for that:

scatter(x0,t)

plot() and scatter() (and most of Matlab's functions) are meant to be used with vectors, which can take some time to get used to if you are used to traditional programming languages. Just as you didn't need a loop to create the vector x0, you don't need a loop to use plot().

Upvotes: 1

hessam hedieh
hessam hedieh

Reputation: 820

You are adding one point in Y axis along a line in X Axis use this code

t=linspace(0,8,11)
xs=(1.+t).^0.5
x0=xs./(1.+t)
m=size(t)
n=max(m)
hold on
for k=1:n
plot(x0(1:k),t(1:k),'-')
hold on
end

for more fun and see exactly how for is performed use this for loop

for k=1:n
pause('on')
plot(x0(1:k),t(1:k),'-')
hold on
pause(2)
end

Upvotes: 0

Related Questions