0
coeff = [8 3 3];  %%poly_function 
A = []; N=9;
for ix = 1:N;
    c = 0;
for i = 1:3
    temp=1;
    for k=1:i
        temp=mod(temp*ix,N);
    end
    c = c + mod(coeff(i)*temp ,N);
    c = mod(c, N);
    if c == 0; c = N; end
end
A = [A c]; %%A = [5 7 6 2 4 3 8 1 9]
end

I'm a bit confused about how this loop works to get result A. Why is A defined as A= [ ]; and in the end are A and c merged?

Could you please help me understand the working of this code?

AMAN77
  • 6,218
  • 9
  • 45
  • 60
mayfly
  • 1
  • 2
  • It helps to add the relevant language tag to your question (seems to be Matlab). –  Mar 10 '17 at 07:23

1 Answers1

0

Setting A=[] just initializes A as an empty matrix (or vector) that you can add things to later. When you have A = [A c]; it is appending c to A. This is where the polynomial value c is being added to A for each term from 1:N.

Note that best practice is not to append elements to a vector in a loop but rather to pre-allocate using A=zeros(1,N) which creates A just once. Then you can add the values c each iteration using A(ix)=c. This is more efficient but won't make much of a difference if N is small.

Teddy Ort
  • 756
  • 6
  • 7
  • Sir, is there any specific reason that after calculating c = c + mod(coeff(i)*temp ,N);. what c = mod(c, N); does? – mayfly Mar 20 '17 at 11:41
  • `c = mod(c, N)` will ensure that `c` is between `0` and `N`. Even though `mod(coeff(i)*temp ,N)` already ensures that what is added to `c` is modulo `N`, since it is added, it could push `c` past the modulus which is why `mod` is used again. – Teddy Ort Mar 20 '17 at 12:25
  • If I define a simple matrix and want to arrange it's original positions. `mat = [1 2 3; 4 5 6; 7 8 9];` `B=reshape(mat);` `B=[1 4 7 2 5 8 3 6 9];` As per matrix indexing, the elements of B will get arranged by positions defined by A. `mat_new=B(A);` `mat_new=[5 3 8 4 2 7 6 1 9];` `dec = mat_new;` `dec(A) = dec` %dec=[1 4 7 2 5 8 3 6 9] . How does `dec(A)=dec` works to get original matrix back? – mayfly Mar 22 '17 at 16:59
  • Since this is not related to the original post, it would be better if you created a new question. Others might have the same question and they are unlikely to find it in a comment. – Teddy Ort Mar 22 '17 at 18:57
  • Sir, I have already created one but didn't get any response. This is the link: http://stackoverflow.com/q/42714860/6893790 – mayfly Mar 23 '17 at 02:54