If-else-statement not working properly

I am trying to display a plot in customary units if x = 0 or the same plot in metric units if x = 1. However, no matter whether I enter 0 or 1 for x, the program returns only the metric plot. The customary plot works fine if I take out that part of the code and run it separately. Am I missing something in the syntax?
prompt = ' Enter 0 for customary units or 1 for metric units: ';
x = input(prompt);
if x == '0';
disp(Tcust);
sc = [custWS1; custWS2; custWS3; custWS4; custWS5; custWS6; custWS7; custWS8; custWS9; custWS10];
hc = [3; 8; 13; 33; 55; 155; 245; 382; 519; 656];
semilogy(sc,hc);
title('Boundary Layer Plot');
xlabel('Wind Speed, mph');
ylabel('Height, ft');
else x == '1';
disp(Tmet);
sm = [metWS1; metWS2; metWS3; metWS4; metWS5; metWS6; metWS7; metWS8; metWS9; metWS10];
hm=[0.9; 2.44; 3.96; 10; 16.8; 47.2; 74.7; 116; 158; 200];
semilogy(sm,hm);
title('Boundary Layer Plot');
xlabel('Wind Speed, m/s');
ylabel('Height, m');
end

 采纳的回答

In:
x = input(prompt);
‘x’ is a double-precision numeric value, not a string, so:
if x == '0'
will always return false.
Try this:
if x == 0
and:
elseif x == 1
and see if those changes do what you want.

4 个评论

Hey, thanks for the input.
I tried elseif instead of else and now the program returns nothing when it runs, whether I enter 0 or 1. Nothing happens.
My pleasure.
This emulates your if block, and returns the appropriate resluts:
x = input('Give me an ‘x’! ');
if x == 0
fprintf(1, 'x is 0\n')
elseif x == 1
fprintf(1, 'x is 1\n')
end
Give me an ‘x’! 0
x is 0
Give me an ‘x’! 1
x is 1
I can’t run your code, so testing the if block (successfully) is the best I can do.
It works.
On second glance, I realized I missed your point about x not being a string. I changed that and the elseif statement worked perfectly. Thank you so much!
As always, my pleasure!

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Scatter Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by