2017-09-24 8 views
-1

私はMatlabプロジェクトで作業しています。私はコード内のコメントに指示を記載しています。関数を呼び出すときに何も起こりません

%This function will take the number that you put in and give you a 
%value 
%of how many numbers it had to do the mathematical operations on to 
%get to the number 1. 
%If the number inputted is even, start by dividing it by 2. If the 
%result is even, then repeat the process. If the result is odd, then 
%multiply the result by 3 and then add 1. Keep doing this until the 
%number is 1. 

function [s, m] = collatz(num) 
%INPUTS 
%num = the number that the user inputs 
%OUTPUTS 
%s = the number of steps it took to reach the number 1 
%m = the maximum value in that list 

veclist = []; %Creates an empty vector which will hold the list of  
       %numbers 

while num ~= 0 %While the number is not equal to zero 
    if num > 0 %If this number is greater than zero 
     if rem(num,2) == 0 %If the number is even 
      num = num/2; %divide the number by 2 
      veclist = [veclist, num]; %add the number to the vector 

     else %This says if the number is odd 
      num = (num*3) + 1; %Multiply that number by 3 and add 1 
      veclist = [veclist, num]; %Add that number to the list 

     end 
    end 
end 

s = length(veclist) %shows how many elements are in the vector 
m = max(veclist) %shows the max value in the vector 

end 

関数を呼び出すときに何も起こらないことを誰かに教えてもらえますか?

私は「(5)collat​​zの」と言うと、それはあなたの元の質問への答えはcollatz.mは、MATLABパス上ではなかったということです何も

+0

アクティブなフォルダのようなサウンドが正しくない( 'pwd'を参照)か、ファイル名が間違っています(おそらく' collat​​z.m 'でしょう)。 –

+0

@ Dev-iLアクティブなフォルダを変更するにはどうすればよいですか?私は私のファイル名をcollat​​z.m – user3011219

+0

に設定しています。通常、 'cd'を使用して、例:' cd c:\ path \ to \ collat​​z'です。 –

答えて

2

を返しません。これを解決する最も簡単な方法は、ファイルが存在する場所に現在のディレクトリ(cdコマンドを使用)を変更することです。例えば。

cd /Users/farazbukhari/Google Drive/School/MATLAB/Programming Projects/Programming Project 

何も得られない理由は、無限ループがあるからです。あなたの停止条件は、数字が「1に等しい」ときで、のループチェックはなぜwhileですか?現在のコードが1になると、それは奇数として扱われ、4になり、次に2、次に14,2,1 ... 、無限になります。

この場合、ループの状態をwhile num > 1に変更するのが簡単です。

最後に、veclistに新しい値を正しく追加していませんでした。この値は、veclist = [veclist, num];に変更することで解決しました(これはパフォーマンス面では理想的ではありません)。代わりに、適切なサイズのveclist(例:veclist = zeros(10*num,1))を事前に割り当てて、カウンタを増分して、最後に書き込まれた位置を示すようにしてください。このようにして、ソリューションが進行するにつれてますます大きなベクトルを作成することを回避できます。最後にすべてのゼロ値を最後からトリムするだけです。 veclist(veclist == 0) = [];

+0

がわかりました私は、whileループ条件を変更し、なぜそれ、私は理解していないnum>は0 場合、それは私が 言っライン19上で立ち往生ているように見える時に実行「collat​​zの(5)」 – user3011219

+0

私はまだ何も得ていないのですここにこだわっている – user3011219

+1

私の悪い。 'num> 1'である必要があります。また、囲む 'if ... end'ステートメントは不要です。 –

関連する問題