Path: news.mathworks.com!not-for-mail
From: "John D'Errico" <woodchips@rochester.rr.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: mod function
Date: Sun, 13 Mar 2011 22:09:05 +0000 (UTC)
Organization: John D'Errico (1-3LEW5R)
Lines: 37
Message-ID: <iljfa1$7ci$1@fred.mathworks.com>
References: <ilj59c$src$1@fred.mathworks.com>
Reply-To: "John D'Errico" <woodchips@rochester.rr.com>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1300054145 7570 172.30.248.37 (13 Mar 2011 22:09:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 13 Mar 2011 22:09:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869215
Xref: news.mathworks.com comp.soft-sys.matlab:715575

"pluton schmidt" wrote in message <ilj59c$src$1@fred.mathworks.com>...
> Hi all,
> 
> in matlab, is there a function modb similar to mod that works as follows:
> 
> X and Y are positive integers :
> modb(Y,X) is Y if Y<X
> modb(X,X) is X 

I've had occasional use for this, so I wrote clockmod.

HTH,
John

function m = clockmod(n,k)
% clockmod - clock style mod arithmetic, mod(n,k) when that is non-zero, but k when it would be zero otherwise
% usage: m = clockmod(n,k)
%
% arguments: (input)
%  n,k - standard arguments to mod(n,k)
%
%  m   - array of the same size and shape that
%        mod(n,k) would generate, but when that
%        result would have been zero, it contains k.

% just the mod, most of the time
m = mod(n,k);

% but when that result would be zero, return k instead.
ind = (m == 0);
if any(ind(:))
  if numel(k) == 1
    m(ind) = k;
  else
    m(ind) = k(ind);
  end
end