在 Matlab 中从命令行运行特定的单元格部分?

2023-12-08

我在脚本中手动循环遍历 Matlab 中的各个单元(我们称之为 foo.m):

%%
%Code for cell 1

%%
%Code for cell 2

从 Matlab 的命令行中,我希望能够有选择地运行单元格 2 中的代码。文档仅包含如何以交互方式执行此操作的说明(例如,将光标放在适当的单元格中,然后等等)。我想要一些命令行的东西,这样我就可以执行类似 foo.runCell(1) 的操作来运行上面单元格 1 中的代码。

如果没有办法做到这一点,我将把单元格分成单独的脚本/函数。这不太方便,因为我处于“非常快速地磨出原型”的编码模式,所以现在希望所有内容都在一个文件中。


Dev-iL使用java等提供了一个很好的答案...我将在这里提供一个替代方案,它不使用java或编辑器,而是读取文件并在请求时评估语句。

为此,它有一个先决条件,即文件已保存(我认为这不是交互运行单元格/代码块的先决条件)。

无论如何,我认为这是一个“古怪”的问题,并认为我应该尝试一下答案。

这是我的脚本(cellScript.m),其中包含代码块(请注意,我在“%%”之后为每个块指定了​​名称:

%Note: for this method your NOT allowed to put comments at the end of lines
%% cellA
disp ( 'running cell A' ); 
disp ( 'finished cell A' );
%% cellB
disp ( 'running cell B' );
disp ( 'finished cell B' );
%% cellC
disp ( 'running cell C' );
for ii=1:100
  aa(ii) = randi(1);
end
% cells can have comments
disp ( 'past 1st coment' );
   % cells comments can be indented
disp ( 'past indented comment' );

  %{
   block 
   comment
  %}
disp ( 'past block comment' );

% cells can have comments
% multiple lines of comments
  % not lined up
%
%and empty

disp ( 'past multiple lines of comments' );

disp ( 'finished cell C' );
%% cellD
disp ( 'running cell D' );

disp ( 'finished cell D' );
%% cellE
disp ( 'running cell E' );
disp ( 'finished cell E' );

我创建了一个类来完成所要求的工作(我称之为 cellRunner.m )

classdef cellRunner < handle
  properties ( SetAccess = private )
    fileName
    fileInfo
    cellInfo
    cellNames = {};
  end
  methods 
    function obj = cellRunner ( file ) % constructor
      if nargin == 0                        
        obj.fileName = 'cellScript.m';      % default file for testing
      else
        obj.fileName = file;                % store user file
      end
      obj.parseFile();                      % read the file into memory
    end
    function obj = parseFile ( obj )
      if ~isempty ( obj.fileInfo )                        % on parsing check to see if its been parsed before
        if isequal ( obj.fileInfo, dir ( obj.fileName ) ) % Check date stamp (has cell file been modified
%           disp ( 'file not changed - reading skipped' );  % if not skip
%           reading 
          return
        end
      end
      obj.fileInfo = dir ( obj.fileName );                % store file info
      fid = fopen ( obj.fileName );                       % open file for reading
      if fid ~= -1
        index = 0;                                        % this is the index of each cell
        inCell = false;                                   % has it found a cell to start reading
        lines = cell(0);                                  
        while ( true )
          line = fgetl ( fid );                           % read the line in the file
          if line == -1; break; end                       % check for the end of the file
          sLine = strtrim ( line );                       % trim any white space
          if length ( sLine ) > 2 && strcmp ( sLine(1:2), '%%' ) % check to see if its the start of a cell
            if index > 0                                  % Store the last cell data                
              obj.cellInfo{index} = lines;                % in class to run when required
            end
            index = index + 1;                            % increment the index
            obj.cellNames{index} = strtrim ( sLine(3:end) ); % save the name of the cell
            lines = cell(0);                              % re-initialise the lines var
            inCell = true;                                % the start of the cells have been found
          elseif inCell                                   % if reading a cell array
            lines{end+1} = line;                          % add each line to the lines var
          end          
        end
        if index > 0                                      % make sure and save the last cell when finished reading
          obj.cellInfo{index} = lines;
        end
        fclose ( fid );
      else
        error ( 'cellRunner:fileError', 'unable to read file' );
      end
    end
    function obj = runCell ( obj, arg )
      % obj.runCell ( 'cellName' );
      % obj.runCell ( index );
      obj.parseFile();                                    % check that the file hasn't been changed
      if ischar ( arg )                                   % if user provided a char then search for it
        index = strcmp ( arg, obj.cellNames );            % find the index
        if ~any ( index )                                 % check it was found
          error ( 'cellRunner:notFound', '%s not found', arg ); 
        end
      else
        index = arg;                                      % if index is an integer (not checked - assumed if not char)
        if index < 1 || index > length ( obj.cellInfo )   % check integer is valid
          error ( 'cellRunner:notFound', 'Index %d not found', arg );
        end
      end
      commands = obj.cellInfo{index}{1};                  % start to build the command to execute.
      inBlock = false;
      for ii=2:length(obj.cellInfo{index})                % loop around - ignoring any commented lines.
        nextLine = strtrim ( obj.cellInfo{index}{ii} ); 
        if inBlock
          if length ( nextLine ) == 2 && strcmp ( nextLine, '%}' );
            inBlock = false;
          end
          continue
        end
        if length ( nextLine ) == 2 && strcmp ( nextLine, '%{' );
          inBlock = true;
          continue
        end
        if length ( nextLine ) >= 1 && strcmp ( nextLine(1), '%' )
          continue;
        end
        commands = sprintf ( '%s;%s', commands, obj.cellInfo{index}{ii} ); % build a parge string to eval
      end
      evalin('base',commands);                            % eval the expression in the base workspace.
    end
  end
end

然后使用代码如下:

obj.cellRunner();
% Individual cells can be run in two ways:

% By providing the name of the cell (the string after the %%)
obj.runCell ( 'cellC' );
% By providing the index
obj.runCell ( 3 );

Note回想一下,必须保存文件才能使其工作。

示例运行:

whos
obj = cellRunner ( 'cellScript.m' );
obj.runCell ( 'cellC' );
running cell C
past 1st coment
past indented comment
past block comment
past multiple lines of comments
finished cell C
whos
  Name      Size             Bytes  Class         Attributes

  aa        1x100              800  double                  
  ans       1x1                112  cellRunner              
  ii        1x1                  8  double                  
  obj       1x1                112  cellRunner              

注 1 - 为什么要处理类?我从句柄类继承,因为我只想要已读取的文件数据的一份副本 - 请参阅在这个问题中回答1有关何时使用值/处理类的精彩概述。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Matlab 中从命令行运行特定的单元格部分? 的相关文章

  • 直方图均衡结果

    I am trying to code histogram equalization by my self but the results are different from the built in function in matlab
  • getappdata 在 MATLAB 中返回空矩阵

    我有一段代码 我在其中使用setappdata然后我使用以下方式调用数据getappdata即使它不为空 它也会返回一个空矩阵 我的一段简化代码如下 function edit1 Callback hObject eventdata han
  • Numpy 相当于 MATLAB 的 hist [重复]

    这个问题在这里已经有答案了 由于某种原因 Numpy 的 hist 总是返回比 MATLAB 的 hist 少 1 个 bin 例如在 MATLAB 中 x 1 2 2 2 1 4 4 2 3 3 3 3 Rep Val hist x un
  • matlab中无限while嵌套在for循环中

    我想做一个while循环 嵌套在for在 Matlab 中循环以查找数据中不同对之间的距离 我的数据具有以下形式 ID lon lat time 1 33 56 40 89 803 2 32 45 41 03 803 3 35 78 39
  • 禁止 MATLAB 自动获取焦点[重复]

    这个问题在这里已经有答案了 我有以下问题 在我的 MATLAB 代码中 我使用如下语句 figure 1 更改某些数据的目标数字 问题是 在此 MATLAB 之后 系统将焦点集中在具有该图形的窗口上 当我在后台运行一个大脚本并尝试在计算机上
  • 将 kinect RGB 和深度值转换为 XYZ 坐标

    我正在寻找一种简单的方法将 kinect RGB 和深度值转换为 XYZ 坐标 使用 MATLAB 我的目标是一个输入为以下内容的函数 每个点的 RGB 和深度值Kinect相机 并输出 每个点的 x y 和 z 值 RGB 深度 RGB
  • MATLAB 除法...29/128 应该返回 0 吗?

    我真的不认为这是一个精度问题 答案应该是0 226左右 这是确切的代码 val I i j bucketSize pos val bucketSize I只是我从中获取值的矩阵 以下是 MATLAB 的输出 val 29 bucketSiz
  • MATLAB - 通过垂直连接子矩阵重新排列矩阵

    我在执行以下任务时遇到问题 假设一个 3x6 矩阵 A 0 2787 0 2948 0 4635 0 8388 0 0627 0 0435 0 6917 0 1185 0 3660 0 1867 0 2383 0 7577 0 6179 0
  • 图像梯度角计算

    我实际上是按照论文的说明进行操作的 输入应该是二进制 边缘 图像 输出应该是一个新图像 并根据论文中的说明进行了修改 我对指令的理解是 获取边缘图像的梯度图像并对其进行修改 并使用修改后的梯度创建一个新图像 因此 在 MATLAB Open
  • 2D 网格的纹理贴图

    我有一组点 x y meshgrid 1 N 1 M 在常规二维上定义 N x M网格 我还有另一组要点 u v 这是原始网格的一些变形 即 u v f x y 但是我没有实际的f导致变形 如何将纹理映射到由定义的 变形 网格u v 即 给
  • 绘制布朗运动 matlab

    首先 我只想说我不太习惯使用matlab 但我需要一个作业 我应该创建一个 布朗运动 我的代码目前如下所示 clf hold on prompt Ge ett input size input prompt numParticles inp
  • MATLAB问题:在图块中引用变量的值[重复]

    这个问题在这里已经有答案了 可能的重复 matlab 绘图标题中的变量 https stackoverflow com questions 5629458 matlab variable in plot title 我想在图中引用 m 文件
  • 图像处理方面的空间和时间表征有什么区别?

    我是学习图像处理的初学者 我对空间和时间表征的概念有点困惑 那么 对于空间表征来说 是不是像一张二维地图 包含了一些关于地图的统计信息呢 就时间特征而言 值是相对于时间的吗 这意味着什么以及我们为何关心 谢谢 当您在不同时间拍摄一系列图像时
  • 基本矩阵错误?

    我试图通过扫描从相机拍摄的两个图像 检测图像中的特征 匹配它们 创建基本矩阵 使用相机内在函数计算基本矩阵 然后分解它以找到旋转和翻译 这是matlab代码 I1 rgb2gray imread 1 png I2 rgb2gray imre
  • 如何在matlab中使矩阵图平滑

    就像上图一样 怎样才能让画面更流畅呢 或者缩小y轴的范围 数据来自二维矩阵 然后我用plot data 请随意提出任何想法 平滑线条的一种方法涉及样本点之间数据的非线性插值 当你这样做时plot x y o http www mathwor
  • 如何从 Matlab 运行 R 脚本 [重复]

    这个问题在这里已经有答案了 我有 m 文件 我想用它来运行 R 脚本 我怎样才能做到这一点 Matlab文件 caller m some matlab code need to call a R script some matlab cod
  • 二维随机微分方程 (SDE)

    我第一次研究随机微分方程 我正在寻求模拟和求解二维随机微分方程 模型如下 dp F t p dt G t p dW t where p 是一个 2 1 向量 p theta t phi t F是列向量 F sin theta Psi cos
  • GO TO 语句 - Fortran 到 Matlab

    我一直在努力将此网格搜索代码从 Fortran 转换为 Matlab 但是我无法正确合并 GO TO 语句 我正在尝试使用 while 循环 但我认为我需要其他东西来结束搜索 任何帮助将不胜感激 vmax 1 0E 15 amax G 1
  • 在 Matlab/Java 中将手部运动建模为 3D 曲线

    我只需要一些关于我遇到的问题 在哪里查看等的指导 我在我的一个项目中使用了运动跟踪手套 它返回每个手指和手掌的 X Y 和 Z 值 我想做的是首先根据这些坐标创建每个手指运动的表示 然后将它们每个附加到手掌的运动 以获得手的表示 一旦我完成
  • 计算向量的导数

    我有以下函数 维维亚尼曲线 Phi t cos t 2 cos t sin t sin t 只需检查它是否有效 s linspace 0 T 1000 plot3 cos s 2 cos s sin s sin s 如何推导函数Phi 可能

随机推荐