My script is working wrong with nested for loops

3 次查看(过去 30 天)
d = input('enter a number:')
figure
for b = 0:0.5:d
plot(b, 0, '*k')
pause(0.05)
end
for c = 0:0.5:d
plot(0, c, '*k')
plot(d, c, '*k')
pause(0.05)
end
for b = 0:0.5:d
plot(c, d, '*k')
pause(0.05)
end
I couldn't run this script nested for-end loops. How can I do that? It is working correct like this. I want to make lines thinner. I couldn't use Linewidht correctly probably. Can I use axes command differently or use something else?
  3 个评论
sky2
sky2 2021-3-24
I tried to to say I couldn't run this script when I try to use nested loops. Sorry for that.
Jan
Jan 2021-3-24
But there are no nested loops and no need for nested loops. If you have a problem with some code, which contain nested loops, post this code and explain the problems.

请先登录,再进行评论。

采纳的回答

DGM
DGM 2021-3-24
编辑:DGM 2021-3-24
I'm not sure what you were trying to nest here. Would something like this suffice?
a = input('enter a number:')
clf
figure(gcf)
axes('NextPlot', 'add', ...
'XLim', [-1, a+1], 'YLim', [-1, a+1], ...
'DefaultLineMarkerSize', 3);
for s=1:3
for b = 0:0.5:a
switch s
case 1
plot(b, 0, '*k')
case 2
plot(0, b, '*k')
plot(a, b, '*k')
case 3
plot(b, a, '*k')
end
pause(0.05)
end
end
for b = 0:0.5:a
plot([0, a, a, 0, 0], [0, 0, a, a, 0], '-k')
end
As far as the lineweight goes, I don't know how thin you want it to be. You can set the linewidth property:
plot([0, a, a, 0, 0], [0, 0, a, a, 0], '-k','linewidth',0.1)
but the thinnest line that it can display is 1px wide.

更多回答(1 个)

Jan
Jan 2021-3-24
Plotting the line does not need a loop:
% for b = 0:0.5:a % The body does not depend on b, so omit the loop
plot([0, a, a, 0, 0], [0, 0, a, a, 0], '-k')
% end
What is the problem with which line width?
plot([0, a, a, 0, 0], [0, 0, a, a, 0], '-k', 'LineWidth', 3)
  3 个评论
sky2
sky2 2021-3-24
Oh my bad. If I want to use hold on instead of using axes. Do I need to write markersize every plot line right?
Jan
Jan 2021-3-24
"use hold on instead of using axes" - this is not meaningful. hold on sets the NextPlot property of the axes to 'add'. You can do this directly also.
You can either define the MarkerSize inside each plot command, or as default in the axes object. It is a question of taste.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by