xlim not working in 'loop' plots..
7 views (last 30 days)
Show older comments
a=[1 2 3]; %input
for i =1 :1:3
b=a.*3;
c=a.*10;
end
subplot(1,4,1)
for i=1:3
plot(a,b);
end
xlim=([1 30])
subplot(1,4,2:4)
for i=1:3
plot(a,c);
end
xlim=([1 100])
2 Comments
Jan
on 28 Jul 2022
Whenever you mention in the forum, that there is a problem, take the time to describe, what the problem is. "Is not working" is too lean. Explain the difference between the wanted and the obtained result or post a copy of the complete error message. This will increase your chances to get a useful answer fast.
Answers (1)
Jan
on 28 Jul 2022
Edited: Jan
on 28 Jul 2022
You do not call the function xlim() at all, but create a variable with the same name. Replace:
xlim=([1 100])
by
xlim([1 100])
without the = operator, which assigns a value to a variable.
The code contains several other problems:
a=[1 2 3]; %input
for i =1 :1:3
b=a.*3;
c=a.*10;
end
This executes the same assignments 3 times. The body of the loop does not depend on the loop counter, so you can omit the loop:
a = [1 2 3]; %input
b = a * 3;
c = a * 10;
Using the elementwise multiplication .* is not a problem here, but for multiplications with scalar the * operator is fine also.
subplot(1, 4, 1)
for i = 1:3
plot(a, b);
end
xlim([1 30]) % Without =, see above
This plots the same line 3 times. If there was no hold('on') command before, plot() removes all formerly drawn objext from the axes. So this is just a waste of time.
subplot(1, 4, 2:4)
for i = 1:3
plot(a, c);
end
xlim([1 100])
Same problem as above: The loop is useless.
Note that there is a method, to define the XLimits using an assignment instead of a function:
AxesH = axes; % Or: AxesH = subplot(1, 4, 1), which replies the axes' handle also
AxesH.XLim = [1, 100];
Now XLim is not a variable, but a property of the Axes object.
Summary:
a = [1, 2, 3];
b = a * 3;
c = a * 10;
subplot(1, 4, 1);
plot(a, b);
xlim([1, 30]);
subplot(1, 4, 2:4);
plot(a, c);
xlim([1, 100]);
The readability of code is increased, if you insert spaces around operators. Writing vectors without separators saves some milliseconds during typing, but can cost hours for debugging. See:
[1 0]
[1+ 0]
[1 + 0]
[1 +0]
With commas as separators, the result does not not depend on blanks anymore and this is a good programming practice.
0 Comments
See Also
Categories
Find more on Subplots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!