【问题标题】:matlab - is there a function which echo text of file ?matlab - 是否有回显文件文本的功能?
【发布时间】:2013-06-26 08:53:22
【问题描述】:

由于不可能have a script and a function definition in the same file,我想回显我想在脚本中附加的函数,这样我就得到了一个带有函数代码的脚本,然后是这个函数的一些用法。

例如——

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

你对此有什么想法吗?

【问题讨论】:

  • -1:你到底为什么要这样做?除了课堂使用之外,我真的不知道这有什么用,甚至在那里;为什么不直接打开编辑器?
  • @RodyOldenhuis :你说得对,它是供课堂使用的 - 我应该编写一个函数,然后展示我是如何使用它的,所以我创建了一个脚本,我编写了 type 的函数然后一些用法使用此功能,最后使用publish 选项将其所有输出导出为pdf。

标签: matlab


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你可以用这个:

    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
    

    【讨论】:

    • 哇!!正是我要找的:-)
    • @Shai:我现在刚试过。也很棒!所以 HughNolan 的功能已经存在 ....
    【解决方案3】:

    为了完整起见,还有 dbtype 前置行号。

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多