脚本中使用 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 %fn', x(i), y(i));
end
fclose(fileID);
现在我使用 MATLAB 的 system
将命令通过管道传输到 gnuplot:
% Call gnuplot to do the plotting tasks
system('gnuplot &plot ''xt.txt'' &exit &');
但是,我没有正确构造这最后一条指令,因为它只打开 gnuplot 控制台但不执行命令。
此外,与其在中间步骤中将数据保存在文本文件中,我更喜欢使用这种直接方法。
我应该如何正确构建我的system
指令?
注意:Linux有一个类似的问题,我正在运行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 %fn', 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 4.6 (Linux) 在任何情况下都使用 -p 或 --persist 选项挂起。您可以在Windows中的gnuplot版本上检查它。
x = 0:10;
y = randi(100,size(x));
str="/usr/bin/gnuplot -p -e "plot '-' using 1:2n";
for i = 1:numel(x)
str=strcat(str,sprintf('%f %fn',x(i),y(i)));
end
str=strcat(str,"e"n");
system(str)
此外,正如@Daniel所说,您对字符串长度有限制,因此使用临时文件绝对比使用长命令更好。
这个答案是基于John_West答案,非常有帮助。我已经将他的GNU Octave代码翻译成MATLAB语法。
我发现这个页面有助于理解GNU Octave和MATLAB在代码语法方面的差异。这个页面有助于理解GNU Octave字符串上的转义序列(实际上,与C相同)。
这些是我所做的转换:
- 将字符串分隔符替换为
'
"
"
将转义序列替换为"
- 将转义序列替换为
''
'
此外,我进行了以下转换:
- 在存在转义序列的任何地方使用
sprintf
。 - 重新排列转义序列的使用,因为
strcat
删除尾随 ASCII 空格字符。(您可以在文档和此答案中阅读有关此内容的信息)。
将临时脚本与 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 %fn', 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 窗口。在您关闭绘图窗口之前,MATLAB 不会恢复脚本的执行。如果您想要连续的执行流程,您可以使用以下命令自动保存绘图(例如作为.png,以及其他格式):
fprintf(f2,'set terminal png; set output "figure.png"; plot ''xy.txt'' using 1:2');
正如John_West在他的评论中所解释的那样。
使用一个长命令
这种方法正在探索中。还没有取得成功的结果(至少John_West,我没有得到任何情节)。我从John_West答案转录时包含我的 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
来手动恢复执行。