How do I find the least possible value in Matlab, given the modulo values and its remainder values in an array? for example:
A=[ 23 90 56 36] %# the modulo values
B=[ 1 3 37 21] %# the remainder values
which leads to the answer 93
; which is the least possible value.
EDIT:
Here is my code but it only seems to display the last value of the remainder array as the least value:
z = input('z=');
r = input('r=');
c = 0;
m = max(z);
[x, y] = find(z == m);
r = r(y);
f = find(z);
q = max(f);
p = z(1:q);
n = m * c + r;
if (mod(n, p) == r)
c = c + 1;
end
fprintf('The lowest value is %0.f\n', n)
Okay, so your goal is to find the smallest
x
that satisfiesB(i) = mod(x, A(i))
for eachi
.This page contains a very simple (yet thorough) explanation of how to solve your set of equations using the Chinese Remainder Theorem. So, here's an implementation of the described method in MATLAB:
You should note that this algorithm works only for moduli (the values of
A
) which are coprime!In your example, they are not, so this will not work for your example (I've put an
assert
command to break the script if the moduli are not coprime). You should try to implement yourself the full solution for non-comprime moduli!P.S
Also note that the
gcd
command uses Euclid's algorithm. If you are required to implement it yourself, this and this might serve you as good references.