Question

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)?

Was it helpful?

Solution

map=containers.Map({'+','-','*','/'},{@plus,@minus,@mtimes,@mdivide});
f=map('+');
value=f(numbers(1),numbers(2))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top