if-statement with conditions.

58 views (last 30 days)
KETAN PATEL
KETAN PATEL on 14 Jun 2019
Commented: Rik on 29 Mar 2021
Write a function called picker that takes three input arguments called condition, in1 and in2 in this order. The argument condition is a logical. If it is true, the function assigns the value of in1 to the output argument out, otherwise, it assigns the value of in2 to out.
This is a problem from a course that I am taking on Coursera. I get a correct output for "true" but the output for the "false" condition is always wrong. Please, any kind of help will highly appreciated.
Annotation 2019-06-14 203145.png
Here is my code:
function out = picker(condition,in1,in2)
if true
out = in1;
else
out = in2;
end
end
  8 Comments
Rik
Rik on 29 Mar 2021
@Harish C S That is why it is a question. If it were correct, why bother posting the question? See the comments and answers in this thread for working code.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 14 Jun 2019
You can safely delete this assignment:
condintion = in1 < in2;
because it overwrites the ‘condition’ argument.
You can also just use:
if conditon
You don’t have to test it again.
Also, check your spelling!
  4 Comments
Rik
Rik on 17 Jun 2020
Which code? And as Star Strider suggests: check your spelling, including in the code he posted.

Sign in to comment.

More Answers (4)

Sneham Shrikant Vaidya
Sneham Shrikant Vaidya on 18 Jul 2020
function out = picker(condition,in1,in2)
if condition == 1;
out = in1;
else
out = in2;
end
\\try this above code

suat karabocek
suat karabocek on 20 Jun 2019
you may use if and else and two conditions including 1 and 0. such as;
your function.........
if condition == 1;
....
....
else condition == 0;
....
....
end
  3 Comments
Ahmed J. Abougarair
Ahmed J. Abougarair on 19 Apr 2020
The picker function required three input argument

Sign in to comment.


amjad khan
amjad khan on 9 Apr 2020
Edited: Walter Roberson on 31 Aug 2020
function out(condition,in1,in2)
if condition>0 % it is logical
out=in1;
else
out=2;
end

Ahmed Salmi
Ahmed Salmi on 17 Jul 2020
function out=picker(condition,in1,in2)
if condition==true
out = in1;
elseif condition==false
out = in2;
end
end
  1 Comment
Walter Roberson
Walter Roberson on 31 Aug 2020
Under what circumstances can it be the case that the condition is not true and also is not false? When you use elseif you imply that there are cases where nothing that has been tested before came out true and also that the current test might not come out true either.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!