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

4 Ansichten (letzte 30 Tage)
Amit Kumar
Amit Kumar am 27 Okt. 2013
Kommentiert: Image Analyst am 27 Okt. 2013
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?

Antworten (2)

Image Analyst
Image Analyst am 27 Okt. 2013
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 Kommentare
Amit Kumar
Amit Kumar am 27 Okt. 2013
Bearbeitet: Amit Kumar am 27 Okt. 2013
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 am 27 Okt. 2013
If you like it, then mark it as Accepted. Thanks.

Melden Sie sich an, um zu kommentieren.


Danilo NASCIMENTO
Danilo NASCIMENTO am 27 Okt. 2013
Bearbeitet: Danilo NASCIMENTO am 27 Okt. 2013
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

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by