Does matlab have a ternary operator? [duplicate] - matlab

This question already has answers here:
Is there a Matlab conditional IF operator that can be placed INLINE like VBA's IIF
(10 answers)
Closed 9 years ago.
I would like to use a C-like ternary operator but in Matlab, how can this be done?
For example:
a = (test == 'yes') ? c : d
where a,c and d are numeric but in Matlab?

A couple of options:
Inline if statement
a = (test == 'yes') * c;
Inline if else statement
a = (test == 'yes') * c + (test ~= 'yes') * d;
or more neatly:
t = test == 'yes'; a = t * c + ~t * d;
This works in the numeric case since test == 'yes' is cast to 0 or 1 depending on whether it's true or not - which can then be multiplied by the desired outcomes (if they are numeric).

To provide an alternative:
t = xor([false true], isequal(test, 'yes')) * [c; d]
or if you want
ternary = #(condition, trueValue, falseValue)...
xor([false true], condition) * [trueValue; falseValue];
...
t = ternary(isequal(test, 'yes'), c, d);

Related

How does a recursive function return the result in scala?

I am currently learning Scala and I am stuck in the following thing:
I have this algorithm which finds in a recursive way the factorial of a number:
def fact(n:Int): Int=
{
if(n == 1) 1
else n * fact(n - 1)
}
println(fact(5))
My question is, why does this line: if(n == 1) 1 does exactly? Does in mean that the function should return one or that n should become 1? I dont understand how this function returns 120 which is the result. Could someone help me udnerstand? I appreciate any help you can provide
Uhm, this is a very broad question.
Since you are asking for basic understanding of the operators of the language. I will try to explain it all to you, but I would recommend you to take a formal introduction to programming course.
In Scala everything is an expression. Thus, the function itself is an expression that evaluates to the assigned block.
In this case the block is just an if / else expression, which takes a predicate to decide which of the two branches to choose. In this case n == 1 checks if n is equals to 1, if that is true, then it returns 1, if not, it returns n * fact(n -1).
Thus, if we execute the algorithm by ourselves using "equational reasoning", we can understand how it works.
fact(3) = if (3 == 1) 1 else 3 * fact(3 - 1) // replace n in the block.
fact(3) = 3 * fact(2) // reduce the if and the subtraction.
fact(3) = 3 * (if (2 == 1) 1 else 2 * fact(2 - 1)) // expand the fact definition.
fact(3) = 3 * (2 * fact(1)) // reduce the if and the subtraction.
fact(3) = 3 * (2 * (if (1 == 1) 1 else 1 * fact(1 - 1))) // expand the fact definition.
fact(3) = 3 * (2 * (1)) // reduce the if.
fact(3) = 6 // reduce the multiplications.
Lets make this method more c oriented.
Maybe now its more clear that there are two branches
1. When n equals 1 - which stops the recursion.
2. Otherwise - multiply the current value of n by the result of calling the fact method with n - 1, which eventually becomes 1 and stops the recursion.
def fact(n:Int): Int=
{
if (n == 1) {
(return) 1;
}
else {
(return) n * fact(n - 1);
}
}
The semicolon is redundant and the the a return keyword is not recommended/necessary.
You can read about it here
So you are left with:
def fact(n:Int): Int=
{
if (n == 1) {
1
}
else {
n * fact(n - 1)
}
}
Which is basically the same as:
def fact(n:Int): Int=
{
if (n == 1) 1;
else n * fact(n - 1)
}

Why !(0 || 1 || 0) is 0?

I am trying to understand Boolean logic and operators.
I found this example but can't understand why this expression will evaluate to the one shown below.
Say, a = 0, b = 1, c = 0
Expression Will Evaluate to
val1 = !(a || b || c); !(0 || 1 || 0) = !(1) = 0
As I see it, val1 is not a or not b or not c, so why it evaluates to not 1 ?
Not(a or b or c) evaluates the or operations first, so it's not the same as (not a) or (not b) or (not c).
Indeed, it's the same as (not a) AND (not b) AND (not c).
Either operand to an OR being true will give a true result, and then the NOT flips that to a false result for the expression as a whole.
As with integer or real number arithmetic, order of operation can greatly alter the result.
.... val1 is not a or not b or not c ...
No, this is incorrect. The 0 || 1 || 0 inside the parenthesis is evaluated first. The example has it right.
Let's say val1 = 1
1 = !(0 || 1 || 0)
1 = !(1) - because it is the only value that is equal to val1
1 = 0 - then it negates it afterwards
Let's go step-by-step.
val1 = !(0 || 1 || 0);
Firstly, 0 || 1 will evaluate to 1, because || means 'true if at least one of them is true, otherwise false', and 1 = true, 0 = false.
So now it is
val1 = !(1 || 0); Here 1 || 0 will again evaluate to 1, because at least one of them is 1. Now we've got val1 = !(1);. ! means the opposite of the input, so !(1) = 0.
As I see it, val1 is not a or not b or not c, so why it evaluates to not 1 ?
Because what you say would be written as val1 = !0 || !1 || !0. Its quite different, because it doesn't have parenthesis. Parenthesis means 'evaluate everything in the parenthesis first'.

Conditional "Or" Statements in MATLAB

I am under the impression that || is the "or" statement in MATLAB. Perhaps someone can explain the confusing behaviour I am seeing:
a = 2;
a == 2 %returns ans = 1 (true)
a == 2 || 3 %returns ans = 1 (true)
a == 3 || 4 %returns ans = 1 (true)??!!
What am I missing here? 'a' is neither 3 or 4, so shouldn't
a == 3 || 4
return ans = 0 (false)?
The expression
a == 3 || 4
is evaluated that way :
a == 3 => false
then
false || 4 => true
if you want to check whether a is equal to 3 or 4 you should write
(a == 3) || (a == 4)
which is evaluated that way
a == 3 => false
then
a == 4 => false
then
false || false => false
Thomas's answer is an excellent explanation of what's going on here; another way that you can compare a variable to multiple answers is using the any() function.
solutions = [3 4];
any(a==solutions);
The a==solutions line creates a matrix the same size as solutions, which contains 1's in indecies which where the conditional is true, and 0's where it is false.
A few more examples:
any(isprime([17:24])); %returns true; 17, 19 and 23 are prime
any(isinteger(sqrt([17:24]))); %(test for square number) returns false; no square numbers in this range
any(mod(magic(3)(:),6)==3); %returns true; 9 mod 6 == 3. Note (:) inserted so that any is evaluated against all entries of the square matrix created by magic
a == 3 || 4 %returns ans = 1 (true)??!!
The reason for the above behaviour is due to the fact that any real number other than '0' in MATLAB is always evaluated to true.
So what is happening here is
The expression a == 3 is evaluated first and found to be false.
Next, expression false || 4 is evaluated.
Since '4' is a real number other than zero, the resulting expression is false || true which is evaluated to true.
To get a desire result use (a == 3) || (a == 4) which is evaluated as false || false which returns false.

Scala for loop value example [duplicate]

This question already has answers here:
Get list of elements that are divisible by 3 or 5 from 1 - 1000
(6 answers)
Closed 7 years ago.
How to do it this problem in Scala? Do it in For-loop.
sum of all the multiples of 3 and 5 below 1000;
Example: 1*3+2*5+3*3+4*5+5*3+6*5 ... so on 999*3+1000*5 = How much?
I don't think that 1000*5 is a multiple of 5 below 1000. 1000*5 is 5000 which is not below 1000.
It seems like what you want is:
(1 to 1000).filter(x => x % 3 = 0 || x % 5 == 0).sum
Which doesn't use a "for-loop". A lot of people would cringe at such a term, scala doesn't really have for-loops. if MUST use the for construct, perhaps you would write
(for (x <- 1 to 1000 if x % 3 == 0 || x % 5 == 0) yield x).sum
which is exactly the same thing as above.
you could also (though I would not recommend it) use mutation:
var s = 0
for { x <- 1 to 1000 } { if(x % 3 == 0 || x % 5 == 0) s += x }
s
which could also be
var s = 0
for { x <- 1 to 1000 if (x % 3 == 0 || x % 5 == 0) } { s += x }
s
If you want to use the principles of functional programming you would do it recursive - better you can use tail recursion (sorry that the example is not that good but it's pretty late).
def calc(factorB:Int):Int = {
if(factorB+1 >= 1000)
3*factorB+5*(factorB+1)
else
3*factorB+5*(factorB+1)+calc(factorB+2)
}
In a for-loop you can do it like
var result = 0
for(i <- 1 to 1000){
result += i*(i%2==0?5:3)
}
After the for-loop result yields the calculated value. The downside is that you're using a var instead of val. Iam not sure if the statement i%2==0?5:3 is valid in scala but I don't see any reasons why it shouldn't.

String Aritmatic using character operators but not using eval

I am trying to write a shortest function code than can add / multiply / divide / subtract them. The only thing is that the operation would be provided in a char data type:
+ = '+'
- = '-'
/ = '/'
* = '*'
I have successfully implemented the same where operator = '+':
>> eval(sprintf('%d %c %d',8, operator, 7))
ans =
15
But is there a way without using 'eval' function we can achieve the same?
====UPDATE=======
The below is what I could reduce :
function value = MathsOperations(numbers,operator)
value(operator == '+') = numbers(1) + numbers(2);
value(operator == '-') = numbers(1) - numbers(2);
value(operator == '*') = numbers(1) * numbers(2);
value(operator == '/') = numbers(1) / numbers(2);
end
How still I can reduce the LOC(lines of code)?
map=containers.Map({'+','-','*','/'},{#plus,#minus,#mtimes,#mdivide});
f=map('+');
value=f(numbers(1),numbers(2))