Reputation: 8717
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)?
Upvotes: 0
Views: 59
Reputation: 36710
map=containers.Map({'+','-','*','/'},{@plus,@minus,@mtimes,@mdivide});
f=map('+');
value=f(numbers(1),numbers(2))
Upvotes: 3