During the application of the Python programming language, if you want to use the Python programming language to call Matlab to plot and save data, you can refer to the following articles to learn more about it, the following is the main content of the article. I hope you will have some gains.
Call Matlab to plot and save data
Recently, during my experiments, I needed to plot and save the obtained data in Matlab. A small problem is that there are not only data in the original data file, but also some comments before the data, each line starts ). It is troublesome to use Matlab to plot data directly. Because data cannot be processed directly, you can extract the data separately and save it as a file.
Or you need to use Matlab to write a program to filter text. However, Matlab is not its strength in text processing. I am not satisfied with either of these two methods. Python once again provides me with a solution. On the one hand, the Python programming language has strong text processing capabilities, and on the other hand, Python provides direct calls to interactive programs such as Matlab, therefore, it is undoubtedly appropriate to write a Python script to complete this task. The following is the implementation code:
- import os
- import string
- 1filepath = "d:\\\\exp\\\\chgeff_lar_1"
- 2filename="chgeff_lar_1"
- 3id = open(filepath, 'r')
- 4lines = fid.readlines()
- 5fid.close()
- 6x = []; y = []
- 7for line in lines:
- 8if line[0]=="#" or len(line)==1:
- 9continue
- 10else:
- 11xval, yval = string.split(line)
- 12x.append(float(xval))
- 13y.append(float(yval))
- 14id = open(filename+'.m', 'w')
- 15fid.write("""
- 16x = %s
- 17y = %s
- 18plot(x, y)
- 19xlabel('Particle diameter (nm)')
- 20ylabel('Charging efficiency')
- 21print -deps %s.eps
- 22pause(10)
- 23""" % (x, y, filename))
- 24fid.write("exit")
- 25fid.close()
- 26cmd = "d:\\\\matlab6p5\\\\bin\\\\win32\\\\matlab.exe -nodesktop -r " + filename
- 27os.system(cmd)
|
The above 6-13 sentences implement two functions. One is to filter the text (8-9 sentences). By checking the first character of each line and the length of the Line, remove the comment line and empty line. The second is to automatically allocate each row of data read to two variables x and y (10-13 sentences ). Python then writes a set of Matlab code (16-24 sentences) to the file filename. m. Finally, the system function of the OS module is used to call Matlab plot and save (26-27 sentences ). From this example, we can see that the ability of the Python programming language to work together with other languages is relatively strong.