1

I was trying the if test for the first time, well actually so does with function.

Here's the script:

function trial()
  I = input("f INPUT > Manually input frequency value? (yes/no):");
  if I = "yes"; 
    f = input("Please input the frequency value : \n") 
  elseif I = "no";
    f = randi([100 1000],5,5)
  endif
O = 2*pi*f;
fprintf("%.2f \n",O); 
plot(f,O);
xlabel("Frequency");
ylabel("Angular Frequency");
end
    f INPUT > Manually input frequency value? (yes/no):"no"
    Please input the frequency value :

There are 2 things that I don't understand:

  1. Why do I have to write the condition with quotation marks? (i.e "yes" not yes or "no" not no).
  2. Why the 'no' condition ran the input command when it should've been randi?

Can someone show me how it should be done?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120

1 Answers1

1

I = "yes" assigns the string "yes" to the variable I. To make a comparison, use == like this: I == "yes". But this comparison will only work if the two strings are the same length, and will return an array, not a single equality value. Use strcmp to compare strings: if strcmp(I, "yes").

The input function parses what the user types, so that typing 3 will result in the number 3, not the string "3". If you add a second input argument like this: input("prompt","s") then it will not parse the input, and return a string. The user will then be able to type no. See the docs.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120