# How to plot a fixed value for a range in MATLAB?

7 次查看（过去 30 天）
Amit Kumar 2013-10-27

Hello, This appears a simple question but I am not able to solve it. I want to plot a certain value for a range of variables. Obviously, vector sizes are different and I cannot use plot command. Here is what I am trying to do:
A=[5;6];
x=linspace(1,9,3);
for x=1 to 5, A is 5 and for x=5 to 9, a is 6. I want to do this in MATLAB. How to do this? Further, should I use a loop for larger arrays and for a more general plotting? Can you help with this?

### 回答（2 个）

Image Analyst 2013-10-27
Try this:
% Define number of elements.
numberOfElements = 30; % Can be 3 or whatever you want.
x=linspace(1,9, numberOfElements)
% Find index where x = 5
index5 = find(x <= 5, 1, 'last')
% Assign A = 5 up until x = 5.
A(1:index5) = 5;
% Assign A = 5 up until x = 5.
A(index5+1 : numberOfElements) = 6;
% Now plot it.
plot(x, A, 'b*-', 'LineWidth', 2);
grid on;
I tried to make it flexible and general. Of course it could also be made a one-liner (and I'm sure someone will do that) if don't use comments, hard code in numberOfElements, don't plot anything, etc. but I like to write code that is a little more flexible and robust. I hope it wasn't your homework - you should have been honest and applied a tag of homework if it was.
##### 2 个评论显示 1更早的评论隐藏 1更早的评论
Image Analyst 2013-10-27
If you like it, then mark it as Accepted. Thanks.

Danilo NASCIMENTO 2013-10-27

You can do it this way.
clear all;
step=0.1;
i=1;
x=linspace(1,9,3);
for k=x(i):step:x(i+2)
if k>=1 && k<=5
A=5;
else
A=6;
end
end

### 类别

Help CenterFile Exchange 中查找有关 Specifying Target for Graphics Output 的更多信息

### Community Treasure Hunt

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

Start Hunting!

Translated by