1

スクリプトと関数定義を同じファイルに入れることはできないので、スクリプトにアタッチしたい関数をエコーし​​て、関数コードを含むスクリプトを取得し、この関数を使用することを考えました。

例えば ​​-

func1.m

function [result] = func1(x)
    result=sqrt(x) ;  
end

script1.m

echo(func1.m) ; 
display(func1(9))  

script1.mの望ましい出力

function [result] = func1(x)
        result=sqrt(x) ;  
    end
display(func1(9)) 
3

それについて何か考えはありますか?

4

3 に答える 3

7

複雑な解決策がすでに提案されているので、明白なことを述べないのはなぜですか?

Matlab には、必要なことを正確に実行する組み込みコマンドがあります。それは呼ばれtypeます:

>> type('mean')

これを提供します:

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
于 2013-06-26T09:13:24.700 に答える
1

これを使用できます:

function echo(mfile)
    filename=which(mfile);
    if isempty(filename)
        fprintf('Invalid input - check you are inputting a string.');
        return;
    end
    fid=fopen(filename,'r');
    if (fid<0)
        fprintf('Couldn''t open file.');
    end
    file=fread(fid,Inf);
    fclose(fid);
    fprintf('%s',file);
end

これにより、ファイルが開き、読み取られ、印刷されます。入力を文字列として提供する必要があることに注意してください。つまり、一重引用符で囲み、最後に「.m」を付ける必要があります。

echo('fread.m')

いいえ

echo(fread.m) % This won't work
echo('fread') % This won't work
于 2013-06-26T09:02:50.317 に答える
1

dbtype完全を期すために、行番号を先頭に追加する whichもあります。

于 2013-06-26T10:10:28.893 に答える