How to plot a fixed value for a range in MATLAB?
3 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
回答 (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 件のコメント
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
0 件のコメント
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!