如何从 MATLAB 将命令通过管道传递给 gnuplot

How to pipe commands to gnuplot from MATLAB

我想在 MATLAB 脚本中使用 gnuplot 绘制一些数据,而不是使用自定义 MATLAB 绘图环境。

以下面的例子为例,这里我生成了一些随机数据并将其存储在一个文本文件中:

% Generate data
x = 0:10;
y = randi(100,size(x));

% Store data in 'xy.txt'
fileID = fopen('xy.txt', 'w');
for i = 1:numel(x)
   fprintf(fileID, '%f %f\n', x(i), y(i));
end
fclose(fileID);

现在我使用 MATLAB 的 system 将命令通过管道传递给 gnuplot:

% Call gnuplot to do the plotting tasks
system('gnuplot &plot ''xt.txt'' &exit &');

但是,我没有正确构建最后一条指令,因为它只打开 gnuplot 控制台但不执行命令。

此外,与其在中间步骤中将数据保存在文本文件中,我更愿意做 this direct approach.

我应该如何正确构建我的 system 指令?

注意:Linux有个similar question,我是运行Windows.

使用带有 gnuplot 命令的临时脚本

将所有命令打印到临时文件 plot.gp 并将其传递给 gnuplot

您是 运行 Windows,因此请将 /usr/bin/gnuplot 更改为 gnuplot 可能 有效)或您的完整位置gnuplot 可执行文件( 可以 工作)

% checked to work under octave 3.6.4 + gnuplot 4.6
x = 0:10;
y = randi(100,size(x));

str="/usr/bin/gnuplot -p plot.gp"
fileID = fopen('xy.txt', 'w');
for i = 1:numel(x)
   fprintf(fileID, '%f %f\n', x(i), y(i));
end
fclose(fileID);

f2=fopen('plot.gp', 'w');
fprintf(f2, "plot 'xy.txt' using 1:2");
fclose(f2);

system(str)

使用一个长命令

但是,plot '-' ... 使 gnuplot 4.6 (Linux) 在任何情况下都挂起 -p 或 --persist 选项。您可以在 Windows.

中查看您的 gnuplot 版本
x = 0:10;
y = randi(100,size(x));
str="/usr/bin/gnuplot -p -e \"plot \'-\' using 1:2\n";
for i = 1:numel(x)
str=strcat(str,sprintf('%f %f\n',x(i),y(i)));
end
str=strcat(str,"e\"\n");
system(str)

另外,正如@Daniel所说,你对字符串长度有限制,所以使用临时文件肯定比使用long-long命令更好。

此答案基于 ,非常有帮助。我已经将他的 GNU Octave 代码翻译成 MATLAB 语法。

我发现 this page helpful to understand the differences between GNU Octave and MATLAB, in terms of code syntax. And this page 有助于理解 GNU Octave 字符串上的 转义序列 (实际上与 C 中的相同)。

这些是我进行的转换:

  • " 字符串分隔符替换为 '
  • "
  • 替换\"转义序列
  • ''
  • 替换\'转义序列

此外,我还做了以下改造:

  • 在有转义序列的地方使用sprintf
  • 重新安排 转义序列 的使用,因为 strcat 删除了尾随的 ASCII 白色-space 字符。 (您可以在 the documentation and this answer 中阅读相关内容)。

使用带有 gnuplot 命令的临时脚本

这种方法非常有效。

% checked to work under Matlab R2015a + gnuplot 5.0 patchlevel 1
x = 0:10;
y = randi(100,size(x));

str = 'gnuplot -p plot.gp';
fileID = fopen('xy.txt', 'w');
for i = 1:numel(x)
   fprintf(fileID, '%f %f\n', x(i), y(i));
end
fclose(fileID);

f2 = fopen('plot.gp', 'w');
fprintf(f2, 'plot ''xy.txt'' using 1:2');
fclose(f2);

system(str)

此脚本将打开带有绘图的 gnuplot window。在您关闭绘图 window 之前,MATLAB 不会恢复脚本的执行。如果你想要一个连续的执行流程,你可以使用以下命令自动保存绘图(例如,作为 .png 等格式):

fprintf(f2,'set terminal png; set output "figure.png"; plot ''xy.txt'' using 1:2');

正如 John_West 在他的 中解释的那样。

使用一个长命令

这种方法正在探索中。目前还没有成功的结果(至少 John_West 我没有得到任何情节)。我包含了我从 John_West answer:

转录的 MATLAB 代码
x = 0:10;
y = randi(100,size(x));
str = sprintf('gnuplot -p -e "plot ''-'' using 1:2');
for i = 1:numel(x)
str = strcat(str, sprintf('\n%f %f', x(i), y(i)));
end
str = strcat(str, sprintf('\ne"'), sprintf('\n'));
system(str)

此代码不会自行终止,因此您需要通过在 MATLAB 命令行中输入命令 e 来手动恢复执行。