Matlab Error: "Undefined function or method X for input arguments of type 'double'" With Recursion

StackOverflow https://stackoverflow.com/questions/19068548

  •  29-06-2022
  •  | 
  •  

문제

I'm trying to make Sierpinski triangles with recursion but I get this error:

??? Undefined function or method 'sierpinski' for input arguments of type 'double'.

I understand that it has to do with Matlab not finding the path for my function, but the weird thing is that it can find my main sierpinski(x,y,n)-function but not the same function that I'm trying to call later in order to get recursion.

My code looks something like this:

function sierpinski(x,y,n)
...
sierpinski(x2,y2,n-1)
end
sierpinski([0,1,0.5],[0,0,1],4)

I would be very grateful if someone could help me with this :)

도움이 되었습니까?

해결책

I cannot reproduce the first error you report. It probably has to do with the file not being on the path. The easiest way to avoid this is to change the working directory to the directory that contains the .m file.

The second error you describe in your comment is due to the fact that you're trying to have a file that is a Matlab function and a Matlab script at the same time. Both have the extension .m, but the first contains a function definition (something that can be called with arguments, has local variables, and can return values), and the other one contains a series of matlab statements that are to be executed exactly as if they were entered one by one in the command window.

Do the following:

– Make a Matlab function file sierpinski.m which includes only your function code:

function sierpinski(x,y,n)
hold on
if n == 0
    fill(x,y,'r')
else
    x2 = [(x(2)-x(1))/2, (x(2)-x(3))/2, x(3)+(x(2)-x(3))/2];
    y2 = [y(1), y(3)/2, y(3)/2];
    sierpinski(x2, y2, n-1)
end

Save the file to the current directory or a directory on the path.

– In the command window, enter the statement sierpinski([0,1,0.5],[0,0,1],2). The result is a figure window with a skewed red triangle. Not a Sierpinski triangle, but I guess the first step is done. ;-)

Instead of entering that statement in the command window, you can also make a Matlab script file. Edit a file with the name e.g. run_sierpinski.m, which contains the statement:

sierpinski([0,1,0.5],[0,0,1],2)

Again, save the file to the current directory or a directory on the path.

Now you can run the script, either by clicking the "Run" button in the GUI (green triangle or so), or by entering run_sierpinski in the command window. Either way, the result should be the same as entering the statement directly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top