调用函数时没有任何反应

时间:2017-09-24 15:01:08

标签: matlab

我正在开发一个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

有人可以告诉我为什么在调用函数时没有任何反应。

我说“collat​​z(5)”并且它什么都不返回

1 个答案:

答案 0 :(得分:2)

原始问题的答案是collatz.m不在您的MATLAB路径上。解决此问题的最简单方法是将当前目录(使用cd命令)更改为文件所在的位置。例如。

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

你什么都得不到的原因是你有一个无限循环。你说你的停止条件是数字“等于1”,那么为什么while循环检查0?当前代码到达1时,它只会将其视为奇数,将其变为4然后2然后1然后4,2,1 ... ad infinitum

在这种情况下,快速解决方法是将循环条件更改为while num > 1

最后,您没有正确地向veclist添加新值,而是通过将其更改为veclist = [veclist, num];来解决(虽然这在性能方面并不理想)。相反,您应该预先分配一个合理大小的veclist(例如veclist = zeros(10*num,1)),并保持一个递增的计数器,指示写入的最后一个位置。这样,您可以避免在解决方案进展时创建越来越大的向量。最后,只需从末端修剪所有零值,例如veclist(veclist == 0) = [];