Programing

MATLAB에서 동일한 파일에 스크립트와 함수 정의가있을 수 있습니까?

crosscheck 2020. 10. 17. 09:11
반응형

MATLAB에서 동일한 파일에 스크립트와 함수 정의가있을 수 있습니까?


함수 가 있고 스크립트 인 f()에서 사용하고 싶다고 가정 my_file.m합니다.

  1. 에 정의 된 함수를 가질 수 my_file.m있습니까?
  2. 그렇지 않은 경우 f.m. 어떻게 부르 my_file.m나요?

온라인 설명서를 읽었지만이를 수행하는 가장 좋은 방법이 무엇인지 명확하지 않았습니다.


R2016b 릴리스부터 다음 과 같이 스크립트에 로컬 함수 를 사용할 수 있습니다 .

data = 1:10;            % A vector of data
squaredData = f(data);  % Invoke the local function

function y = f(x)
  y = x.^2;
end

R2016b 릴리스 이전에는 MATLAB 스크립트 내에서 정의 할 수있는 유일한 함수 유형은 익명 함수 였습니다. 예를 들면 :

data = 1:10;            % A vector of data
f = @(x) x.^2;          % An anonymous function
squaredData = f(data);  % Invoke the anonymous function

익명 함수는 단일 표현식으로 정의되어야하므로 간단한 작업에 더 적합합니다. 더 복잡한 함수의 경우 자체 파일에서 정의하고 MATLAB 경로의 어딘가에 배치 하여 스크립트에 액세스 할 수 있도록 한 다음 다른 함수와 마찬가지로 스크립트에서 호출해야합니다.


이 제한을 극복하는 방법은 스크립트를 인수가없는 함수로 바꾸는 것입니다 (전역 네임 스페이스의 변수가 필요한 경우 함수에 명시 적으로 전달하거나 "evalin"을 사용하여 가져옵니다).

그런 다음 "스크립트"에서 필요한 모든 추가 기능을 정의 할 수 있습니다. 해킹이지만 몇 가지 사소하지 않은 기능이 필요한 경우 매우 강력하다는 것을 알았습니다.

편집 : 여기에 단순한 예가 있습니다. 이 모든 것이 단일 파일에있을 수 있습니다.

function [] = myScriptAsAFunction()
   img = randn(200);
   img = smooth(img);
   figure(1);
   imagesc(img);
   axis image;
   colorbar;
end

function simg = smooth(img)
    simg = img / 5;
end

다음과 같이 할 수 있습니다 (파일 이름이이라고 가정 my_file.m).

function my_file
   %script here
end

function out = f(in)
   %function here
end

실행 버튼을 클릭하면 my_file기본적으로 기능 이 실행됩니다.


1) 스크립트 안에 함수를 중첩 할 수 없습니다.

2) fm이 경로 또는 현재 디렉토리에 있는지 확인하고 다른 함수처럼 호출 할 수 있습니다.


R2016b 부터 스크립트 내에서 로컬 함수를 정의 할 수 있습니다.

x = 1;
y = add1(x);

function z = add1(x)
    z = x + 1;
end

John의 솔루션을 구현 했으며 유용하다는 것을 알았습니다. 그러나 몇 가지주의 사항이 있습니다 (Octave에서는 Matlab이 유사하게 작동 할 수 있음).

  1. If code inside your main function contains clear all prior to using the auxiliary function, it will not work. In file test3.m, commenting/uncommenting clear all makes code work/not work.

    function [] = test3()
      %clear all
      a = myfunc( 1 );
      a
    endfunction;
    
    %---------------------------------
    % Auxiliary functions
    
    function retval = myfunc( a )
      retval = 2 * a;
    endfunction;
    

    From It seems like upon running a script, there is a first pass where code outside functions is executed (in this case, there is no such code), and functions defined (in this case, test3 and myfunc) are added to the workspace. A second pass would execute the main function, which would not find myfunc if clear all is active.

  2. As pointed out by chessofnerd, out-of-the-box the variables in your main function do not go to the workspace.


You can have many functions in a sample file. But only the first one can act as a main function, when you run the file. Others can be used merely in this file. For some situation you want to define a big function. You can separate it into smaller functions and define below it.

However, the most simple way to find the answer is having a try~

참고URL : https://stackoverflow.com/questions/5363397/in-matlab-can-i-have-a-script-and-a-function-definition-in-the-same-file

반응형