Conditional Statement with 3 different ranges

12 ビュー (過去 30 日間)
Matthew Garrelts
Matthew Garrelts 2016 年 2 月 1 日
コメント済み: Matthew Garrelts 2016 年 2 月 1 日
I am given the three ranges
h < r
r≤h<H−r
H − r ≤ h ≤ H
I am trying to make the program run v1 when the first range applies, then v2 when the second range applies, and v3 when the third range applies. Simulating a tank with rounded ends filling up. I feel that using the if statements are what's needed.
H is the max height of the tank, h is the current level of the water, and r is the radius of curvature of the ends of the tank.
Then the final values need to be plotted.
-------------------
r = 2; %ft
H = 7; %ft
h = 0:.1:H;
if (h<r)
v1 = (1/3)*pi*h^2*(3*r-h)
elseif (r<=h<(H-r))
v2 = (2/3)*pi*r^3+pi*r^2*(h-r)
else ((H-r)<=h<=H)
v3 = (4/3)*pi*r^3+pi*r^2*(H-2*r)-(1/3)*pi*(H-h).^2*(3*r-H+h)
end
plot(h,v?)
Any help is much appreciated as I don't know where to go next.

回答 (1 件)

Guillaume
Guillaume 2016 年 2 月 1 日
You cannot use the notation if a<b<c to check that b is between a and c in matlab (in fact, I'm not aware of any programming language where that is valid). a<b<c is interpreted as (a<b)<c. The result of (a<b) is either true (1) or false(0), so your comparison ends up as being 0<c or 1<c. To express what you want you need to use logical operators (& or && if scalar, in this case).
Therefore your tests are:
h < r
r <= h & h < (H-r)
(H-r) <= h & h < H
You can't use these test with if though because h is a vector. The simplest way to obtain what you want is to use logical indexing:
r = 2; %ft
H = 7; %ft
h = 0:.1:H;
v = zeros(size(h));
%temporary variables to help with logical indexing:
v1 = 1/3*pi*h.^2.*(3*r-h); %Important: note the .^2 and .* to work with vectors
v2 = 2/3*pi*r.^3+pi*r.^2.*(h-r); %Again .^3 .^2 and .*
v3 = 4/3*pi*r.^3+pi*r.^2*(H-2*r)-1/3*pi.*(H-h).^2.*(3*r-H+h);
%use logical indexing to assign v1, v2 and v3 to the relevant portion of v
v(h < r) = v1(h < r);
v(r <= h & h < (H-r)) = v2(r <= h & h < (H-r));
v((H-r) <= h & h < H) = v3((H-r) <= h & h < H);
plot(h, v);
  1 件のコメント
Matthew Garrelts
Matthew Garrelts 2016 年 2 月 1 日
Thank you very much!

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

カテゴリ

Help Center および File ExchangeInputs についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by