Stop the for loop

I want to stop a loop when the the modulo 26 of the determinant times a 'number', then use such 'number' to multiply the inverse of a matrix. The code is:
clc, clear;
A=input('Symmetric matrix: ');
format rat;
d=det(A)
Minv=inv(A);
M1=(Minv*d);
for i=1:100
j=mod(d*i, 26);
x=i;
if j==1, break, end
end
x
Z=round(mod((M1*x), 26))
However I can't make the for loop to stop when the value of 'j' becomes 1 and use the value of 'x' to multiply the matrix; every time the value of x is the final value of 'i', in this case 100.

1 Commento

Oleg Komarov
Oleg Komarov il 29 Mag 2012
Why do you expect the modulus of d*i should ever be 1?

Accedi per commentare.

 Risposta accettata

Geoff
Geoff il 29 Mag 2012

1 voto

Time for the most basic of debugging practises...
After you calculate j, put in the following line of code:
disp(j);
Now, run your loop.
I'm willing to bet that j is either always even (because d is even), or is a sufficiently fractional non-integer.
When you work out what's happening and fix it, then consider the following. From a 'performance' perspective (well, really it's about not doing unnecessary things), just save the value into x once:
x = [];
for i = 1:100
if mod(d*i,26) == 1
x = i;
break;
end
end
if isempty(x)
disp('Not found');
end
Doesn't really matter here, but it's worth getting into the habit of recognising some repeated calculations as being pointless. Call it "eco-coding". =)

3 Commenti

Adrian
Adrian il 29 Mag 2012
I tried to display 'j', after trying different matrices the '1' comes up a few times in each one however the if statement doesn't break the for loop; using your code when the value of x is just saved once it doesn't save any value there as the for loop doesn't stop in there either.
Geoff
Geoff il 29 Mag 2012
Then it's probably not _exactly_ 1. Try this:
fprintf( 'i=%d : j=%.30f\n', i, j);
You might need to test with something like:
if abs(j-1) < eps(10)
Adrian
Adrian il 29 Mag 2012
That was it! The only thing I had to finish so my encryption/decryption program was finished. I am just starting to learn matlab and your help is really appreciated.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Prodotti

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by