使用php在网页执行matlab
通过php调用linux命令,可以实现远程调用matlab.
试验环境:Fedora16, matlab2012b linux version, Google chrome 18.0.1025.108 beta
以下代码实现了在网页输入matlab命令并显示执行结果。注意:如果不加-nodisplay选项,会出现" no display specified"的警告,当然可以在执行matlab命令之前unset DISPLAY也可以直接在terminal执行matlab。
如果你仅仅想远程调用matlab函数,可以参考mathworks的php webservice相关文档,此处也可以参考官方关于python调用的文档。
以下代码对于plot()等绘图命令会出现{Warning: Objects of graph2d.lineseries class exist - not clearing this class or any of its super-classes}错误,目前未解决(也就是无法绘图)。但是通过ssh远程登陆服务器调用相同命令可以plot并save图像,不解。
输入ver命令获取版本信息
直接终端运行
参考资料:
mathwork关于matlab启动参数的介绍:
http://www.mathworks.cn/help/techdoc/matlab_env/f8-4994.html
SpecifyingMATLAB Startup Options
Youcan specify startup options (also called command flags or commandline switches) that instruct the MATLAB program to perform certainoperations when you start it. On all platforms, you specify theoptions as arguments to the matlab command when you start is at theoperating system prompt. For example, the following starts MATLAB andsuppresses the display of the splash screen.
matlab-nosplash
OnWindows platforms, you can precede a startup option with either ahyphen (-) or a slash (/). For example, -nosplash and /nosplash areequivalent.
Onall platforms, you can also specify startup options using a MATLABstartup file—see Specifying Startup Options in the MATLAB StartupFile
OnWindows platforms, you can specify startup options in the MATLABshortcut—see Including Startup Options in a Shortcut on WindowsSystems.
andselect Properties from the context menu. TheProperties dialog box for MATLAB opens to the Shortcut pane.
Inthe Target field,after the target path for C:\Program Files\MATLAB\R2010b\bin\matlab.exe -r "results"
Includethe statement in double quotation marks (... matlab.exe -r "D:\results.m"
Usesemicolons or commas to separate multiple statements. This examplechanges the format to ... matlab.exe -r "format('short');results"
Separatemultiple options with spaces. This example starts MATLAB withoutdisplaying the splash screen, and then runs the MATLAB codefile ... matlab.exe -nosplash -r "results"SpecifyingStartup Options in the MATLAB Startup File
Atstartup, MATLAB automatically executes the file addpath /home/Placethe startup.m filein the default or current startup folder, which is where MATLAB firstlooks for it. For more information, see .CommonlyUsed Startup Options
Thefollowing table provides a list of some commonly used startup optionsfor both Windows and UNIX? platforms.For more information, including a complete list of startup options,see the Platform Option Description
All
Set
All
Displaystartup options (without starting MATLAB).
All
Automaticallywrite output from MATLAB to the specified log file.
Windowsplatforms
StartMATLAB with the desktop minimized. Any desktop tools or documentsthat were undocked when MATLAB was last closed will not beminimized upon startup.
UNIXplatforms
StartMATLAB without loading the Sun Microsystems JVM? software. Thisminimizes memory usage and improves initial startup speed, butrestricts functionality. With
All
StartMATLAB without displaying its splash screen.
All
Automaticallyrun the specified statement immediately after MATLAB starts. Thisis sometimes referred to as calling MATLAB in batch mode. Filesyou run must be in the startup folder for MATLAB or on the searchpath. Do not include path names or file extensions. Enclose thestatement in double quotation marks (
All
LimitMATLAB to a single computational thread. By default, Windowsmakes use of the multithreading capabilities of the computer onwhich it is running.
PassingPerl Variables on Startup
Youcan pass Perl variables to MATLAB on startup by usingthe function test(x)
Tostart MATLAB with the function matlab -r "test(10)"
Onsome platforms, you might need to use double quotation marks:
matlab -r "test(10)"
Thiscommand starts MATLAB and runs #!/usr/local/bin/perl $val = 10; system('matlab -r "test(' . ${val} . ')"');
Invokethe Perl script at the prompt using a Perl interpreter.
Formore information, see the Startupand Calling Java Software from the MATLAB Program
Whenthe MATLAB program starts, it constructs the class path for SunMicrosystems Java software using RunningMATLAB without graphic interfaceInteractiveover SSH
StartMATLAB using the command:
matlab -nodisplay -nojvm
Runninga MATLAB script over SSH
Inthis case, you don't even need a MATLAB Prompt to interact with.
matlab -nodisplay -nojvm -r a_code > matlab.out
YourMATLAB program should have the file name First,go to the directory containing the MATLAB script that defines thefunction (or, fancier, add that directory into MATLAB PATH byediting your MATLABPATH environment variable or pathdef.m file).Then, run like this Again,you can redirect the output to a file. Youcan also write a Shell, Perl or Python script to do so. MATLAB givesan example using Perlat http://www.mathworks.com/help/techdoc/matlab_env/f8-4994.html Writea job script below and submit it using YourMATLAB program should have the file name a_code.m. Formore options on starting MATLAB, please refer to its official docat =============================================================================================================================== Linux下后台运行matlab 命令如下: nohupmatlab <name.m> name.out & 同样:matlab< name.m >& name.out & 就够了,不用nohup。 =============================================================================================================================== http://www.danpearce.co.uk/php_and_matlab Thefollowing example describes how to use PHP to run MATLAB commands.With there being so many different possible system configurations,it is likely that you may have to modify these steps slightly foryour own use. I am using: MATLABR2009a WindowsVista Apache2.2.11 Inthis example, we will create a MATLAB function that generates a textfile of random numbers. The location of this file is user definedfrom an HTML form. We use PHP to link the two together. First,we need create a very basic MATLAB function that creates a plaintext file. The only input is a filename. Obviously, you'd want someslightly more robust checks normally. Using any plain text editor,copy and paste the following code and save as phpcreatefile.m (makea note of the file path as you'll need it later): Noticethe last line of this file. The 'Quit' command is necessary toterminate MATLAB when we're finished. Next,we need to create a file that renders an HTML form that, whensubmitted, opens MATLAB and calls the function phpcreatefile with afilename taken from the form. copy and paste the following code intoa php file: Theabove code first creates an extremely basic HTML form that asks theuser for a filename. When submitted, the form submits to self,making the filename available as a $_POST variable. Next, a block ofPHP code checks to see if the form is submitted. If it is, we startto try and build the appropriate command to send to MATLAB. $filename= the filename submitted by the user from our form $inputDir= the path to the folder that you saved phpcreatefile.m in (this isonly really necessary if the function phpcreatefile is saved in afolder that is not included in PATH) $outpurDir= the path to the folder we are going to create our text file in $command= Here, we're building a command line string required to runMATLAB. Lets break it down a bit further: matlab= the command we pass to CMD in order to start MATLAB -sd"startdir" specifies the startup directory for MATLAB:in this case we set it to match the location of our functionphpcreatefile -r"statement" starts MATLAB and executes the specifiedMATLAB statement. exec($command)executes our command line string as if you'd entered it in thecommand window Nextare a couple of lines that report back to our user what MATLAB hasjust done Thatsit. You just ran MATLAB using PHP Foundthis useful? Do you have comments or possible improvements to thisexample? Please leave your comments at the bottom. Onething that is immediately apparent is that at no time can MATLAB beseen running while the above code executes. This is because PHP runsas a module of an Apache service. Vista (and maybe other systemstoo) has a security layer that deals with how services interact withthe desktop. The problem is better described here. =============================================================================================================================== 出现的问题: /usr/local/MATLAB/R2012a/bin/matlab-nojvm -nosplash -r "ls;exit;"Warning: No displayspecified. You will not be able to display graphics on the screen. <M A T L A B (R) > Copyright 1984-2012 The MathWorks, Inc. R2012a(7.14.0.739) 32-bit (glnx86) February 9, 2012 To get started, typeone of these: helpwin, helpdesk, or demo. For product information,visit www.mathworks.com. >> http://www.mathworks.com/matlabcentral/newsreader/view_thread/165074 =============================================================================================================================== Subject: errormessage " no display specified" From: PeterJohansson Date: 4Mar, 2008 15:57:01 Message: 1of 2 Replyto this message Addauthor to My Watch List Vieworiginal format Flagas spam DearFriends, Subject: errormessage " no display specified" From: roberson@ibd.nrc-cnrc.gc.ca(Walter Roberson) Date: 4Mar, 2008 20:07:35 Message: 2of 2 Replyto this message Addauthor to My Watch List Vieworiginal format Flagas spam Inarticle <fqjrgd$4v4$1@fred.mathworks.com>, =============================================================================================================================== http://mem.bio.pitt.edu/content/calling-matlab-php Submittedby keithc on Mon, 08/23/2010 - 15:26 Iwanted to run a MATLAB command from PHP that would generate afigure, save it to an image file, and display that image in thewebpage. Here is the process I used: Mostnew MATLAB licenses only allow a single specified user to startthe application at any time. If you want to call MATLAB from thecommand-line from an interface like PHP (that for security reasonsis run as another system user), one way to get around thislicensing issue is to masquerade as the licensed user using sudo: The-H is necessary for the HOME environment variables to be changedto the target user. SincePHP won't have a TTY terminal associated with it, you'll have togive the system user that runs PHP/apache the NOPASSWD flag in thesudoers file. Start editing the sudoers file by running Nowyou should craft your exec() call in PHP. The basic syntax forstarting a MATLAB process in the backgroundis: Additionally,if you want to be able to save graphics, I found it necessary toprepend the command with: Pleasenote that there are security issues in giving sudo privileges toyour apache/webserver user, especially with NOPASSWD.Runninga MATLAB script with input variables over SSH
matlab -nodisplay -nojvm -r "my_function(10)"
OnSun Grid Engine (SGE)-powered cluster
#!/bin/sh#$ -V#$ -cwd#$ -S /bin/bash#$ -N matlab#$ -o $JOB_NAME.o$JOB_ID#$ -e $JOB_NAME.e$JOB_ID#$ -q normal #$ -pe fill 12#$ -P hrothgarmatlab -nodisplay -nojvm -r a_code > matlab.out
http://www.mathworks.com/help/techdoc/ref/matlabunix.html
其中name.m是你自己的M文件.
更完整的写法应该是:
nohupmatlab < name.m >& name.out &UsingMATLAB with PHP
The MATLABfile
function phpcreatefile(filepath)% Open the filefid = fopen(filepath, 'wt');for i = 1:100 % Create random number randNumber = [num2str(rand(1)) '\n']; % Write number to file fprintf(fid, randNumber);end% Close filefclose(fid);% Quit MATLABquit force
The PHP file
<html> <body> <form action="" method="post"> Enter a filename <input type="text" name="filepath"><br /> <input type="submit" /><br /> </form> </body></html><?phpif(isset($_POST['filepath'])) { $filename = $_POST['filepath']; $inputDir = "C:\\output"; $outputDir = "C:\\output"; $command = "matlab -sd ".$inputDir." -r phpcreatefile('".$outputDir."\\".$filename."')"; exec($command); echo "The following command was run: ".$command."<br/>"; echo $filename." was created in ".$outputDir."<br/>";}?>
Notes
ThreadSubject: error message " no display specified"
When I try to open the matlab installed on remoteserver to
work on the files located at the same server,byusing Xterm
on windows XP OS, I get the message "NoDisplay specified.
You will not be able to displaygraphics on the screen."
Please suggest me somesolution.
Thanks
PeterJohansson <johansson2006@hotmail.com> wrote:
>DearFriends,
>When I try to open the matlab installed on remoteserver to
>work on the files located at the sameserver,by using Xterm
>on windows XP OS, I get themessage "No Display specified.
>You will not beable to display graphics on the screen."
On the remotehost, define a global environment variable
named DISPLAY whichis your PC's hostname (or IP address)
followed by ':0'.
Themeans to define this variable will depend upon the shell
youare using, and upon the operating system. For example
forthe original Bourne shell('sh'),
DISPLAY=johansson.hotworks.com:0 exportDISPLAY
For the Korn shell or modern Bourne shell, theabove would work as
would
exportDISPLAY=johansson.hotworks.com:0
For csh and derivatives,you would likely need something similar to
setenv DISPLAYjohansson.hotworks.com:0
On some Unix systems assigningDISPLAY can be done automatically
in /etc/profile by a linesuch as
[ ! -z "${REMOTEHOST:-}" ] &&DISPLAY=$REMOTEHOST:0 export DISPLAY
Once you haveDISPLAY defined on the remote system, you might
need to"authorize" the remote system to display onto yourlocal
system. The mechanisms for that vary according to whichX11 you
are running (e.g., Hummingbird eXceed or cygwin) butthe
typical unix-like mechanism would be to use the 'xauth'command.
xauth has two major modes of operation. The easier ofthe two
is not permitted in some security environments. Itwould look like
xauth +SERVERNAME
such as
xauth+matserv.hotworks.com
Sometimes you have to use IPaddresses for DISPLAY and for xauth .
--
"Productof a myriad various minds and contending tongues, compactof
obscure and minute association, a language hasits own abundant and
often recondite laws, in thehabitual and summary recognition of
whichscholarship consists." -- Walter PaterCallingMATLAB from PHP
sudo-H licenseduser command
sudovisudo
Thenadd the following line:apache-userALL=NOPASSWD: /usr/local/bin/matlab
/usr/local/bin/matlab-r "command;exit;"
Notethat the "exit;" here is necessary so that the MATLABprocess will quit after processing. To run this from PHP we willuse the following command:$command= "sudo -H licenseduser /usr/local/bin/matlab -r"command;exit;"
DISPLAY="";exportDISPLAY;
AndI set the Renderer variable for any Figure objects in MATLAB to"painters" (the default is often opengl, which will notwork for background processes).