필터 지우기
필터 지우기

Problem with storing for-loop values in array

조회 수: 1 (최근 30일)
Alexander Engman
Alexander Engman 2016년 2월 16일
댓글: Jos (10584) 2016년 2월 17일
Hi!
I know the question of storing for-loop values in an array has been asked before.
I am trying to compare the time it takes to perform factorial calculations with two different methods. I will just post one of the methods since it is the only one I am having trouble with.
My code is this:
clear all, close all, clc
n=150; %factorial to calculate
T2=zeros(1,n); %empty (1 x n)-vector
B=zeros(1,n); %empty (1 x n)-vector
p=n;
tic;
for i=1:n
while n>1
n=n-1; %calculates n!
p=p*n; %calculates n!
B(1,n)=p %store values of factorial in (1 x n)-vector
end;
T2(i)=toc; %times the function
end;
plot(T2,B) %plots the function
The problem I am having is that, instead of storing each value of p in one of the columns of the vector B and thus being able to track the growth of the factorial, all of the columns of the vector B, except for the last one which is just showing the final value. All of the values of p seem to be accurate.
How can I write this to instead store each value of the factorial in its own column in the vector B?
I hope I made it possible to understand my question!
Thanks in advance.

채택된 답변

Jos (10584)
Jos (10584) 2016년 2월 16일
After the first iteration of the for-loop n has become 1. So for the next iteration, the while-loop is never entered. so T(k) will be almost the same as T(k-1), and B(k) will be zero, for k > 1.
  댓글 수: 4
Alexander Engman
Alexander Engman 2016년 2월 17일
편집: Alexander Engman 2016년 2월 17일
Basically, I want to calculate any factorial but a requirement is that the factorial is recursive. But I suppose that the code you wrote would count as a recursive formula since it is using F2(k-1)? From what I understand that is the whole point of a recursive formula.
Then I want to be able to plot the time it takes for Matlab to calculate the factorial and plot it in a value/time diagram. But I think I will manage to figure it out now thanks to your help.
Many thanks!!
Jos (10584)
Jos (10584) 2016년 2월 17일
for and while loops do not truly represent recursion. The function below does:
function Y = recurF(X)
% recurF - calculates the factorial of X using recursion
if X < 2
Y = 1 ;
else
Y = X * recurF(X-1) ;
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Frequency Transformations에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by