MATLAB: N-Term Approximation for Matrices

matricesmatrixmatrix arraymatrix manipulation

Hello,
Utilizing a function I created to calculate the N-term approximation for a matrix:
function[eA]= N_Approx( N,A,I )
sum=0;
for i=1:N
ai=(A^i)/(factorial(i));
sum=sum+ai;
end
eA=I+sum;
I would like to solve this function over a range of values of N however when I set my range for N (ie N=1:10), the approximation function above only outputs a matrix for the last number of the range. Is there a way to store the matrix created for every iteration?
Any help would be appreciated.
Thank you! CAAJ

Best Answer

The power operation is expensive and you can avoid the repeated application:
function Result = N_Approx(N, A, I)
Result = zeros([size(A), N]);
Ai = eye(size(A));
SumAi = I; % If I should be added to each matrix
facti = 1;
for i = 1:N
facti = facti * i; % cumulative product instead of factorial
Ai = Ai * A; % cumulative product instead of power
SumAi = SumAi + Ai / facti;
Result(:, :, i) = SumAi;
end
Even if runtime does not matter in your case, it is a good programming practice to reduce the number of power operations, when possible.
If the variable "I" should not be added to each matrix, use: "SumAi = 0" instead of "SumAi = I" and add I to the final Result only.
You can access the intermediate matrices and the last value by:
Result(:, :, k)
with k goes from 1 to N.
As Walter has said already: There are many of questions in the forum caused by using "sum" as name of a variable, when later in the code it is tried to use as function. Therefore it is recommended to avoid this.
Related Question