0

I want to essentially be able to have a function swap where I can enter 2 arguments. The first would be the central point, the point of inversion so to speak, while the second would be the number I want to find the opposite of, with respect to the point.

So if I put in swap(5,2) it would return 8.
The idea being that 5-2=3 then 5+3=8.

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
Andrew I
  • 11
  • 1

2 Answers2

2

Just write it down on paper:

function out = swap(in1,in2)
% pivot = in1 - in2;
% out = in1 + pivot = in1 + (in1 - in2) = 2*in1 - in2
out = 2*in1 - in2;
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
1

Functional form (in its own .m file or another function file)

function out = swap(x, y)
    out = x + (x-y);
end

% Then in another file / command window
swap(5,2) % >> 8 

Anonymous function (can be defined anywhere within the scope it is used)

swap = @(x,y) x + (x-y);
% Then in same function / script
swap(5,2) % >> 8
Wolfie
  • 27,562
  • 7
  • 28
  • 55