3 件のコメント

Roger Stafford
Roger Stafford 2016 年 12 月 21 日
The problem with your code is that when you apply an ‘if’ to an entire vector, as you have done with “if x<0”, it is not regarded as true by matlab unless all elements of that vector are true, and that of course is not the case, so the ‘if’ will fail. The same hold true with your other two if’s - they will all fail and y is never set.
Stephen23
Stephen23 2020 年 12 月 25 日
Original question asked by Alexandros Dhimas on 20th December 2016 retrieved from Google Cache:
How to plot a polyclonal expression using if statement?
Hello, I' ve got a polyclonal function to plot (using if statement) as shown on this picture:
for -5<x<30.
My thougth on the solution was:
x=linspace(-5,30,1000);
if x<0
y=10*x.^0;
else if x>=0 & x<9
y=10*x+10;
else if 9<=x
y=15*sqrt(4*x)+10;
end
end
end
plot(x,y)
But i get this on the command window "Error using plot A numeric or double convertible argument is expected"
I can't find any mistakes on my code.
Walter Roberson
Walter Roberson 2020 年 12 月 25 日
This is not a Duplicate.

サインインしてコメントする。

 採用された回答

Alexandros Dhimas
Alexandros Dhimas 2016 年 12 月 21 日
編集済み: Alexandros Dhimas 2016 年 12 月 21 日

0 投票

Solution usin if statement:
x=linspace(-5,30,1000);
for i=1:1000
if x(i)<0
y(i)=10;
elseif x(i)>=0 & x(i)<9
y(i)=10*x(i)+10;
else
y(i)=15*sqrt(4*x(i))+10;
end
end
plot(x,y)

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 12 月 20 日

0 投票

Either use a for loop or (better) use logical indexing. http://blogs.mathworks.com/steve/2008/01/28/logical-indexing/
Roger Stafford
Roger Stafford 2016 年 12 月 21 日

0 投票

If you only want to plot the function, do this:
x1 = linspace(-5,0,50); y1 = 10*ones(1,50);
x2 = linspace(0,9,90); y2 = 10*x2+10;
x3 = linspace(9,30,210); y3 = 15*sqrt(4*x3)+10;
plot([x1,x2,x3],[y1,y2,y3])
Another way:
x = linspace(-5,30,400);
y = (x<0)*10+(x>=0&x<9).*(10*x+10)+(x>=9).*(15*sqrt(4*abs(x))+10);
plot(x,y)

カテゴリ

ヘルプ センター および File Exchange2-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