1

I'm currently writing a code in MATLAB that plots the convergence of 1/N!, Where N goes from 1-10. I've created a for loop that calculates 1/N! for each value from 1-10 but how do I add each of the values calcuated in the for loop in a vector array?

clc,clear
Nterms = 10;
total = 0;

for ns = 0:Nterms
    newterm = 1/(factorial(ns));
    disp(['The term ',num2str(ns),' is:',num2str(newterm)])
    total = total + newterm; % Sum of series
end

1 Answer 1

1

Allocate array before the loop (initialize with zeros), and put values to array using ns+1 as index:

clc,clear
Nterms = 10;
total = 0;

% Initialize the array with zeros - allocate memory space
arr = zeros(1, Nterms+1);

for ns = 0:Nterms
    newterm = 1/(factorial(ns));
    disp(['The term ',num2str(ns),' is:',num2str(newterm)])
    total = total + newterm; % Sum of series

    % Store newterm in index ns+1 of arr.
    arr(ns + 1) = newterm;
end

disp(arr);
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh I was along the right line with prelocating the vector size, Thanks you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.