This answer is based on John_West answer, which was very helpful. I have translated his GNU Octave code into MATLAB syntax.
I found this page helpful to understand the differences between GNU Octave and MATLAB, in terms of code syntax. And this page helpful to understand the escape sequences on GNU Octave strings (which are in fact, the same as in C).
These are the conversions I made:
- Replace
"
string delimiter with '
- Replace
\"
escape sequence with "
- Replace
\'
escape sequence with ''
Furthermore, I made the following transformations:
- Use
sprintf
wherever there is an escape sequence.
- Rearrange the use of escape sequences because
strcat
removes trailing ASCII white-space characters. (You can read about this in the documentation and this answer).
Using temporary script with commands for gnuplot
This approach works very well.
% 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)
This script will open a gnuplot window with the plot. MATLAB will not resume the execution of the script until you close the plot window. If you want a continuous flow of execution, you can automatically save the plot (for example as a .png, among other formats) with the command:
fprintf(f2,'set terminal png; set output "figure.png"; plot ''xy.txt'' using 1:2');
as John_West explains in his comment.
Using one long command
This approach is under exploration. No successful results have been achieved yet (at least John_West and I did not get any plot). I am including my MATLAB code as I transcribed it from John_West answer:
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)
This code does not terminate by itself, so you will need to manually resume the execution by entering the command e
in the MATLAB command line.