create a vector that contains all the factorial numbers from 1 to 13 in matlab

One way to create a vector containing all the factorial numbers from 1 to 13 is by using the factorial function in Matlab. Here's the code that creates such a vector using a loop:

main.m
% Initialize an empty vector
factorials = zeros(1,13);

% Calculate all the factorial numbers
for i = 1:13
    factorials(i) = factorial(i);
end

% Display the resulting vector
disp(factorials);
195 chars
11 lines

However, since Matlab supports vectorization, we can achieve the same result more concisely using a single line of code:

main.m
% Calculate all the factorial numbers using vectorization
factorials = factorial(1:13);

% Display the resulting vector
disp(factorials);
138 chars
6 lines

This code creates a vector of integers from 1 to 13 using the colon operator (1:13), then applies the factorial function to each element of the vector using vectorization, and finally assigns the resulting vector to the factorials variable. The resulting factorials vector contains all the factorial numbers from 1 to 13.

Note that the factorial function returns doubles, not integers, so the factorials vector will contain double-precision numbers. If you want to convert the vector to integers, you can use the int64 function:

main.m
% Convert the factorials vector to integers
factorials = int64(factorials);

% Display the resulting vector
disp(factorials);
126 chars
6 lines

related categories

gistlibby LogSnag