eP = zeros(size(P));
for k = 0:N-1
eP = eP + P^k ./ k!;
end
For your second question, you need to indicate what condition should be used to terminate the "while" loop. Detection of the first element which is not greater than 0.5 ? Detection that you have run out of elements? Which order do you want to visit the elements in, considering that P will be a 2D matrix and thus could be traveled randomly or by rows or by columns or by diagonals or by Knight moves...