MATLAB: See, i have this error in the code saying: ??? Attempted to access x(0); index must be a positive integer or logical. Error in ==> abc at 14 x(i)=mod(g^x(i-1), p);

duplicate post requiring mergingindexintegerlogical?positive

clear all; close all; clc;
p = input('Introduceti numarul prim p= ');
g = input('Introduceti numarul prim g= ');
Nr=p-1;
x=zeros(1, Nr);
for i=1:Nr
x(i)=mod(g^x(i-1), p);
end;
disp('Rezultatul este: ');
disp(x);

Best Answer

You start the loop at i=1, but then try and index x(i-1), which is the same as x(0). MATLAB starts indexes at 1 (Mathematical indexing, not programmer indexing).
That is
x = [1 2 3 4];
x(1)
ans =
1
x(0)
Subscript indices must either be real
positive integers or logicals.