Advertisement
obernardovieira

Calculator (with functions)

Dec 3rd, 2014
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 0.89 KB | None | 0 0
  1. function s = nsum(a,b)
  2.     %MatLab have a function called sum
  3.     s = str2num(cell2mat(a))+str2num(cell2mat(b));
  4. end
  5.  
  6. function s = sub(a,b)
  7.     s = str2num(cell2mat(a))-str2num(cell2mat(b));
  8. end
  9.  
  10. function m = multi(a,b)
  11.     m = str2num(cell2mat(a))*str2num(cell2mat(b));
  12. end
  13. function d = div(a,b)
  14.     d = str2num(cell2mat(a))/str2num(cell2mat(b));
  15. end
  16.  
  17. calc = input('Insert some values and the type of calculation (Ex: 53+35): ','s');
  18. not_digit = isstrprop(calc,'digit');
  19.  
  20. for e = 1:1:length(calc)
  21.     if not_digit(1,e) == 0
  22.         numbers = strsplit(calc, calc(1,e));
  23.         result = 0;
  24.         switch calc(1,e)
  25.             case '+'
  26.                 result = nsum(numbers(1,1),numbers(1,2));
  27.             case '-'
  28.                 result = sub(numbers(1,1),numbers(1,2));
  29.             case '*'
  30.                 result = multi(numbers(1,1),numbers(1,2));
  31.             case '/'
  32.                 result = div(numbers(1,1),numbers(1,2));
  33.         end
  34.         fprintf('The result of %s = %d\n',calc,result)
  35.     end
  36. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement