matlab - 有一个回显文件的函数吗?

URL*_*L87 1 matlab

由于不可能在同一个文件中有脚本和函数定义,我想在脚本中回显我要附加的函数,这样我得到一个带有函数代码的脚本,然后使用这个函数.

例如 -

func1.m

function [result] = func1(x)
    result=sqrt(x) ;  
end
Run Code Online (Sandbox Code Playgroud)

script1.m

echo(func1.m) ; 
display(func1(9))  
Run Code Online (Sandbox Code Playgroud)

script1.m的欲望输出

function [result] = func1(x)
        result=sqrt(x) ;  
    end
display(func1(9)) 
3
Run Code Online (Sandbox Code Playgroud)

你有什么想法吗?

Sha*_*hai 7

既然已经提出了一个复杂的解决方案,为什么不说出明显的解决方案呢?

Matlab有一个内置命令,可以完全满足您的需求.它被称为type:

>> type('mean')
Run Code Online (Sandbox Code Playgroud)

会给你这个:

function y = mean(x,dim)
%MEAN   Average or mean value.
%   For vectors, MEAN(X) is the mean value of the elements in X. For
%   matrices, MEAN(X) is a row vector containing the mean value of
%   each column.  For N-D arrays, MEAN(X) is the mean value of the
%   elements along the first non-singleton dimension of X.
%
%   MEAN(X,DIM) takes the mean along the dimension DIM of X. 
%
%   Example: If X = [0 1 2
%                    3 4 5]
%
%   then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1
%                                                     4]
%
%   Class support for input X:
%      float: double, single
%
%   See also MEDIAN, STD, MIN, MAX, VAR, COV, MODE.

%   Copyright 1984-2005 The MathWorks, Inc. 
%   $Revision: 5.17.4.3 $  $Date: 2005/05/31 16:30:46 $

if nargin==1, 
  % Determine which dimension SUM will use
  dim = min(find(size(x)~=1));
  if isempty(dim), dim = 1; end

  y = sum(x)/size(x,dim);
else
  y = sum(x,dim)/size(x,dim);
end
Run Code Online (Sandbox Code Playgroud)