Info
This question is closed. Reopen it to edit or answer.
How do I write a function which computes the first n values of factorial k using a for loop?
1 view (last 30 days)
Show older comments
I need to write a function which computes (without writing anything in the screen) the first n values of k! (factorial of k), which are defined as 1!=1 and k!=k(k-1)! For k>1
Edit- so far I have:
f1=1; %initializes values
for i=1:n % counts from 1 to n
f1=f1*i %multiplies all integers in the interval
end
How do I make the answer output a row vector of the first n values of k?
3 Comments
Star Strider
on 24 Feb 2017
You have to subscript them to create each subsequent calculation as a separate element. Please see my Answer.
MATLAB will create a row vectors unless you tell it to create a column vector.
Jan
on 25 Feb 2017
@Haley: +1 for the question. Asking an own clear question and showing the own effort is the productive and not consuming way to ask for help, even the question concerns homework.
Accepted Answer
Star Strider
on 23 Feb 2017
Multiply each integer by the product of the previous integers to calculate the factorial.
In pseudocode:
N = number to compute the factorial of;
fact = 1; % Initialise
for index = 1:N % Counts From ‘1’ To ‘N’
fact = multiply index by previous values of ‘fact’;
end
6 Comments
Star Strider
on 24 Feb 2017
That is exactly what my code outline does. Reading and understanding what I wrote is not at all difficult!
I could have written the entire loop, or more easily just used the cumprod function. That is not the purpose of helping with homework.
That purpose is to guide the person to a solution, encouraging the person to read the documentation and to experiment with different programming solutions, not provide them.
Jan
on 24 Feb 2017
Edited: Jan
on 25 Feb 2017
@John BG: No, Haley does not want [k! (k-1)! .. (k-n)!] but "the first n values of k!". See his code.
@Haley: All you need to change in your code is to use an index for fact as Star Stride has explained in the comment. Hint: Start the loop at 2, not at 1.
Finally it would be efficient to pre-allocate:
fact = ones(1, N); % Instead of fact = 1
because the iterative growing of arrays is expensive.
More Answers (2)
John D'Errico
on 25 Feb 2017
Edited: John D'Errico
on 25 Feb 2017
Haley has made an honest attempt here, and gotten reasonably close to what is needed. In fact, there was only one problem, in that a vector had to be created.
You want to compute the vector [1!, 2!, 3!, ... n!], as a row vector. The solution is pretty simple.
First, allocate an entire vector. This will make your code efficient. On this problem it won't really matter, but in the future, you will need to learn about preallocation of arrays on problems like this.
function F = myfactlist(n)
% compute the factorials of the numbers 1:n
F = ones(1,n);
for k = 2:n
F(k) = F(k-1)*k;
end
See that I could have allocated most of the vector to be all zeros since I overwrite the successive elements, but I took advantage that I know that the very first element of the vector will be 1.
Will this function work when n==1? Yes, since then F will be just the 1x1 row vector containing the number 1. A for loop that runs from 2 to 1, with an implicit step of 1 just skips the loop completely. So MATLAB just ignores that loop when n is not at least 2.
If you look at the function I've written, you will see that really, it is quite close to what you started with.
The only significant change I made was in defining F as a vector. Then I used indexing to define all the elements of F beyond the first element.
So if we test it out:
F = myfactlist(6)
F =
1 2 6 24 120 720
We see there a row vector, that contains the factorials of the numbers 1:6.
Be careful, as that function will have a problem if n is zero, or a negative number. Those things are easily fixed, but beyond the scope of your question. Good code in general will worry about such problems, it would worry about the case where someone tries to run your code with a non-integer value for n. Another problem case to watch for is if n was provided, but not a scalar. What would it mean if n is a vector? What really matters then is that you have a clear indication of what is needed in those cases, then you need to write code that is robust to all possible inputs. If an error is indicated, then an error should result, or if no error, then your code should return the correct solution always, stably, robustly. Again, well beyond the scope of your question. But these are things you need to watch for as your skills grow.
Yes, there are other ways one could solve the problem. But sometimes a simple, easily read, easily understood solution is all we need. In fact, complex solutions that are difficult to understand can be difficult to debug in the future, difficult to read when you see the code a year later.
Feel free to accept this answer if it helps you.
4 Comments
John BG
on 26 Feb 2017
Mr D'Errico
Haley asks for the 1st n terms of k! that depending upon what side Haley starts reading, provided n<k, then either
1! 2! .. (k-n-1)! (k-n)!
or
k! (k-1)! .. (k-n+1)! (k-n)!
John BG
John D'Errico
on 26 Feb 2017
Edited: John D'Errico
on 26 Feb 2017
John, do you explicitly try to be obtuse? I suppose this is a good thing that you are generally so confused, since you seem to like to do homework for people, which is something that we try not to do here, unless the person has made a serious effort.
Note that k was never specified. Only that the first n terms of the function factorial(k) are required.
In the title, it reads factorial k, so factorial(k) is a function of some variable k.
I don't know about you, but the word FIRST generally means starting at the beginning. The assignment stated:
"which are defined as 1!=1 and k!=k(k-1)! For k>1"
So we start at k=1. Then we compute n values, starting from 1, going up to k=n.
The really funny thing is, you seem to think that the set
1! 2! .. (k-n-1)! (k-n)!
is actually a sequence of n numbers. Sorry, but that is a laughable thing.
As for the second sequence that you write:
k! (k-1)! .. (k-n+1)! (k-n)!
even there, there are n+1 terms in the sequence you have written. Again, you don't seem to be able to count, on top of not thinking about what was asked for.
John BG
on 24 Feb 2017
Edited: John BG
on 24 Feb 2017
Hi Haley
please have a look at the recursive implementation of factorial with anonymous functions.
iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}();
factor = @(f,n) iif(n<=0,0, n<= 1,1, true,@() n*f(f,n-1) );
factor2 = @(n) factor(factor, n);
test
factor2(3)
ans =
6
>> factor2(4)
ans =
24
>> factor2(5)
ans =
120
>> factor2(6)
ans =
720
if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John BG
14 Comments
John BG
on 9 Mar 2017
Edited: John BG
on 9 Mar 2017
It's so obvious that Haley did not understand the term 'you have subscript ..' from Start Strider as the comment that then once after Start Strider answer, Haley again said
And this can be done to output a row vector of the first n values of k?
don't you see? Start Strider may have provided something that Star Strider understood as an answer but Haley did not.
Jan simon, is not what you understand, but what the person originating the question understands, or not.
Haley marked my answer as accepted, some one removed it, I just put it back where the question originator wanted it because I managed to get the message through, and therefore I consider I deserve my answer as accepted.
John D'Ericco did not understand it was about providing a vector until 25th, one day after me, after reading my answer. Isn't obvious who may have removed the marked answer by Haley?
regards
John BG
John D'Errico
on 9 Mar 2017
John - don't make accusations. Stop being so nasty. And stop claiming who knew what at what time. I did not provide an answer until it became obvious that there was confusion as to he question.
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!