Subplot in loop just plotting the first y value?

3 次查看(过去 30 天)
for n=[2:5]
for c=[10,20,40,80]
figure(1)
subplot(1,4,n-1)
x=linspace(0,2*pi,c);
y=atan(x)
plot(y)
end
end
This loop creates four subloops in one window, so far so good. But spent the last eternity trying to get Matlab to plot four different y values, not just four copies of the first.
Pic:
  3 个评论
Stephen23
Stephen23 2016-9-6
This is a good example of why bad code formatting makes it hard to write good code: there are actually two loops, and this is the cause of the problem... however the nested loop is not clear because if the lack of indentation.
Use clear, consistent formatting and it makes writing, reading, and understanding code one million times easier. MATLAB's default formatting is usually perfect, so just use that. TIP: select all of the code and click ctrl+i.
Marcus Silverberg
Wow thanks for the crtl+i command. It did not solve the problem, but I got the idea.

请先登录,再进行评论。

采纳的回答

Adam
Adam 2016-9-6
编辑:Adam 2016-9-6
Try this. I haven't tested it, just changed it off the top of my head, but the idea is what you want even if there are a couple of things you need to fix in the code - i.e. get rid of the nested loops and just index into c so that you do 4 different plots.
c=[10,20,40,80]
for n=1:4
figure(1)
subplot(1,4,n)
x=linspace(0,2*pi,c(n));
y=atan(x);
plot(y)
end
Edit: I have tested now after a couple of fixes to my original and this seems to work.

更多回答(1 个)

Mischa Kim
Mischa Kim 2016-9-6
Marcus, add a
hold on
after the plot command.
  2 个评论
Marcus Silverberg
Thanks, that helped a bit. But now I got all the four values in each of the subplots.. The point is to get c=10 in the first subplot, c=20 in the second..etc.
Mischa Kim
Mischa Kim 2016-9-6
Not quite sure, what you are trying to achieve. If it is only one plot per subplot, why not use indexing?
c = [10,20,40,80];
for n = 1:4
subplot(1,4,n)
x = linspace(0,2*pi,c(n));
y = atan(x);
plot(y,'*')
end

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by