Writing a relatively simple MATLAB function

479 Views Asked by At

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

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

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