0

I'm new to MATLAB and I have been asked to write a MATLAB function whose input arguments are two integers $a$ and $b$; the output is the remainder of the integer division $a/b$ if $a>=b$ or of the integer division $b/a$ if $b>a$

Can someone help me out? Thanks.

EDIT:

This is all I can string together at the moment but I know that it is incorrect. I'm just trying to put together what I know.

function r=remainder(n,m);

if n>=m;

r=rem(m,n);

elseif m>n;

r=rem(n,m);

end

Lewis
  • 3
  • what problem are you encountering exactly? are you asking someone to write the code for you? – user51547 Nov 10 '13 at 23:21
  • Just asking for a start really, I have little experience with MATLAB, I have included the facts I know in the original post but I am not sure how to put it together in a script. – Lewis Nov 10 '13 at 23:23

2 Answers2

0

In MatLab, in general, functions can be write as the followings: function [y1,...,yN] = myfun(x1,...,xM) function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first executable line of the function.

in you case you have one output and two inputs; Function:

function y = compare(a,b)
if a>=b
y = a/b;
else
y = b/a;
end
end

Main Program:

close all; clear all; clc;
a=2;
b=3;
y=compare(a,b)

y =

1.5000

Note: Remember to save both function and your MatLab code in the same folder (same location). and the name of the function is also important to be related to what you want to do.

sky-light
  • 468
  • This doesn't give the remainder of the two inputs though? It just divides the two. What would I need to do to achieve the remainder? – Lewis Nov 10 '13 at 23:34
  • Don't worry I solved it by just replacing the line y=a/b with y=rem(a,b) and vice versa. Thanks for the initial help. – Lewis Nov 10 '13 at 23:51
0

That's very easy. You can do it as a standalone function, defined in its own remainder.m file:

function sol = remainder(a,b)
sol = rem(max(a,b),min(a,b));

Alternatively, you can do it with an anonymous function, which can be defined directly in the command line:

remainder = @(a,b) rem(max(a,b),min(a,b));
Luis Mendo
  • 1,834