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

4 visualizaciones (últimos 30 días)
Amit Kumar
Amit Kumar el 27 de Oct. de 2013
Comentada: Image Analyst el 27 de Oct. de 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?

Respuestas (2)

Image Analyst
Image Analyst el 27 de Oct. de 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 comentarios
Amit Kumar
Amit Kumar el 27 de Oct. de 2013
Editada: Amit Kumar el 27 de Oct. de 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 el 27 de Oct. de 2013
If you like it, then mark it as Accepted. Thanks.

Iniciar sesión para comentar.


Danilo NASCIMENTO
Danilo NASCIMENTO el 27 de Oct. de 2013
Editada: Danilo NASCIMENTO el 27 de Oct. de 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

Categorías

Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by