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

조회 수: 3 (최근 30일)
Amit Kumar
Amit Kumar 2013년 10월 27일
댓글: Image Analyst 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
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
Amit Kumar
Amit Kumar 2013년 10월 27일
편집: Amit Kumar 2013년 10월 27일
Thanks. I was thinking by doing by some identity or unit matrix multiplication to convert variables to same range. But your method is better. By the way, this was not homework!
Image Analyst
Image Analyst 2013년 10월 27일
If you like it, then mark it as Accepted. Thanks.

댓글을 달려면 로그인하십시오.


Danilo NASCIMENTO
Danilo NASCIMENTO 2013년 10월 27일
편집: 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에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by