声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 3730|回复: 8

[编程技巧] 【转帖】使用php在网页执行matlab

[复制链接]
发表于 2012-10-18 06:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
目录
IncludingStartup Options in a Shortcut on Windows Systems
SpecifyingStartup Options in the MATLAB Startup File
CommonlyUsed Startup Options
PassingPerl Variables on Startup
Startupand Calling Java Software from the MATLAB Program
RunningMATLAB without graphic interface
    Interactiveover SSH
    Runninga MATLAB script over SSH
    Runninga MATLAB script with input variables over SSH
    OnSun Grid Engine (SGE)-powered cluster
UsingMATLAB with PHP
    The MATLABfile
    The PHP file
    Notes
ThreadSubject: error message " no display specified"
CallingMATLAB from PHP


回复
分享到:

使用道具 举报

 楼主| 发表于 2012-10-18 06:30 | 显示全部楼层
本帖最后由 Jillian 于 2012-10-18 06:33 编辑

通过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图像,不解。

[php] view plaincopyprint?
  1. <html>  
  2.     <body>  
  3.         <form action="" method="post">  
  4.             输入命令: <input type="text" name="cmd">  
  5.                   <input type="submit" /><br />  
  6.         </form>  
  7.     </body>  
  8. </html>  
  9.   
  10. <?php  
  11. phpinfo();  
  12. if(isset($_POST['cmd']))  
  13. {  
  14. $cmd = $_POST['cmd'];  
  15. $command="/usr/local/MATLAB/R2012a/bin/matlab -nodisplay -nosplash -r ".""".$cmd.""";  
  16. //echo $command."<br/>";  
  17. //$command="/usr/local/MATLAB/R2012a/bin/matlab -r ".""".$cmd.""";  
  18. shell_exec("unset DISPLAY");//删除DISPLAY环境变量  
  19. $out = shell_exec($command);  
  20. $str="< M A T L A B (R) >  
  21.                   Copyright 1984-2012 The MathWorks, Inc.  
  22.                     R2012a (7.14.0.739) 32-bit (glnx86)  
  23.                               February 9, 2012  
  24.   
  25.    
  26. To get started, type one of these: helpwin, helpdesk, or demo.  
  27. For product information, visit www.mathworks.com.";  
  28. $out=ltrim($out,$str);  
  29. $out=rtrim($out,"  
  30. >>");  
  31. echo $out;  
  32. }  
  33. ?>  
复制代码
 楼主| 发表于 2012-10-18 06:32 | 显示全部楼层
相关截图:
输入sin(1:10)进行简单计算 a1.png
输入ver命令获取版本信息

a2.png
直接终端运行
a3.png
 楼主| 发表于 2012-10-18 06:35 | 显示全部楼层
本帖最后由 Jillian 于 2012-10-18 06:41 编辑

参考资料:

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.


IncludingStartup Options in a Shortcut on Windows Systems

Youcan add selected startup options (also called command flags orswitches for the command line) to the target path for your shortcutin the Windows environment for MATLAB. For more information about theoptions, see CommonlyUsed Startup Options.

Touse startup options for the MATLAB shortcut icon in a Windowsenvironment, follow these steps:

  • Right-clickthe shortcut icon for MATLAB

                                   
    登录/注册后可看大图
    andselect Properties from the context menu. TheProperties dialog box for MATLAB opens to the Shortcut pane.
  • Inthe Target field,after the target path for matlab.exe,add the startup option, and click OK.For example, adding -r"filename" runsthe MATLAB code file filenameafterstartup.

Thisexample instructs MATLAB to automatically run the file results afterstartup, whereresults.m isin the startup folder or on the search path for MATLAB. The statementin the Target fieldmight appear as

C:\Program Files\MATLAB\R2010b\bin\matlab.exe -r "results"

Includethe statement in double quotation marks ("statement").Use only the file name, not the file extension or path name. Forexample, MATLAB produces an error when you run

... matlab.exe -r "D:\results.m"

Usesemicolons or commas to separate multiple statements. This examplechanges the format to short,and then runs the MATLAB code file results:

... matlab.exe -r "format('short');results"

Separatemultiple options with spaces. This example starts MATLAB withoutdisplaying the splash screen, and then runs the MATLAB codefile results:

... matlab.exe -nosplash -r "results"
 楼主| 发表于 2012-10-18 06:39 | 显示全部楼层
本帖最后由 Jillian 于 2012-10-18 06:41 编辑

SpecifyingStartup Options in the MATLAB Startup File

Atstartup, MATLAB automatically executes the file matlabrc.m and,if it exists,startup.m.The file matlabrc.m,which is in the matlabroot/toolbox/local folder,is reserved for use by MathWorks and by the system manager onmultiuser systems.

Thefile startup.m isfor you to specify startup options. For example, you can modify thedefault search path, predefine variables in your workspace, or definedefaults for Handle Graphics&#174; objects.Use the following statements in a startup.m fileto add the specified folder, /home/username/mytools,to the search path, and to change the current folder to mytools uponstartup.

addpath /home/username/mytoolscd /home/username/mytoolsPlacethe 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&#174; platforms.For more information, including a complete list of startup options,see the matlab(Windows) referencepage or the matlab(UNIX) referencepage.


Platform
Option
Description
All
-clicensefile
Set LM_LICENSE_FILE to licensefile.It can have the form port@host.
All
-hor -help
Displaystartup options (without starting MATLAB).
All
-logfile"logfilename"
Automaticallywrite output from MATLAB to the specified log file.
Windowsplatforms
-minimize
StartMATLAB with the desktop minimized. Any desktop tools or documentsthat were undocked when MATLAB was last closed will not beminimized upon startup.
UNIXplatforms
-nojvm
StartMATLAB without loading the Sun Microsystems JVM&#8482; software. Thisminimizes memory usage and improves initial startup speed, butrestricts functionality. With nojvm,you cannot use the desktop, figures, or any tools that requireJava software.Forexample, you cannot set preferences if you start MATLAB withthe -nojvm option.However, you can start MATLAB once without the -nojvm option,set the preference, and quit MATLAB. MATLAB remembers thatpreference when you start it again, even if you usethe-nojvm option.
All
-nosplash
StartMATLAB without displaying its splash screen.
All
-r"statement"
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 ("statement").Use semicolons or commas to separate multiple statements
All
-singleCompThread
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 -r optionof the matlabfunction.For example, assume a MATLAB function test thattakes one input variable:

function test(x)

Tostart MATLAB with the function test,use the command

matlab -r "test(10)"

Onsome platforms, you might need to use double quotation marks:

matlab -r "test(10)"

Thiscommand starts MATLAB and runs test withthe input argument 10.

Topass a Perl variable instead of a constant as the input parameter,follow these steps.

  • Createa Perl script such as
    #!/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 matlab(Windows) or matlab(UNIX) referencepage.


Startupand Calling Java Software from the MATLAB Program

Whenthe MATLAB program starts, it constructs the class path for SunMicrosystems Java software using librarypath.txt aswell as classpath.txt.If you call Java software from MATLAB, see more about this in TheJava Class Path and LocatingNative Method Libraries inthe MATLAB External Interfaces documentation.



 楼主| 发表于 2012-10-18 06:42 | 显示全部楼层
本帖最后由 Jillian 于 2012-10-18 06:45 编辑

http://narnia.cs.ttu.edu/drupal/node/41
RunningMATLAB without graphic interface
Interactiveover SSH
StartMATLAB using the command:
  1. matlab -nodisplay -nojvm
复制代码
Runninga MATLAB script over SSH
Inthis case, you don't even need a MATLAB Prompt to interact with.
  1. matlab -nodisplay -nojvm -r a_code > matlab.out
复制代码
YourMATLAB program should have the file name a_code.m (youcan change it to whatever name you like. But when you tell MATLAB torun it, omit the .m suffix.)The >matlab.out partredirects the output to a file rather than showing on your Linux/MacOS X terminal. This way is preferred because you have a record onwhat is happening.

Runninga MATLAB script with input variables over SSH
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
  1. matlab -nodisplay -nojvm -r "my_function(10)"
复制代码
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

OnSun Grid Engine (SGE)-powered cluster
Writea job script below and submit it using qsub

  1. #!/bin/sh
  2. #$ -V
  3. #$ -cwd
  4. #$ -S /bin/bash
  5. #$ -N matlab
  6. #$ -o $JOB_NAME.o$JOB_ID
  7. #$ -e $JOB_NAME.e$JOB_ID
  8. #$ -q normal
  9. #$ -pe fill 12
  10. #$ -P hrothgar
  11. matlab -nodisplay -nojvm -r a_code > matlab.out
复制代码
YourMATLAB program should have the file name a_code.m.
Formore options on starting MATLAB, please refer to its official docat
http://www.mathworks.com/help/techdoc/ref/matlabunix.html
 楼主| 发表于 2012-10-18 06:46 | 显示全部楼层
本帖最后由 Jillian 于 2012-10-18 06:51 编辑

Linux下后台运行matlab  
命令如下:
  1. nohupmatlab <name.m> name.out &
复制代码

其中name.m是你自己的M文件.
更完整的写法应该是:
  1. nohupmatlab < name.m >& name.out &
复制代码

同样:matlab< name.m >& name.out & 就够了,不用nohup。

==============================================================================
UsingMATLAB with PHP
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:

MATLABR2009aWindowsVista
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.

The MATLABfile
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):

  1. function phpcreatefile(filepath)
  2. % Open the file
  3. fid = fopen(filepath, 'wt');
  4. for i = 1:100
  5.     % Create random number
  6.     randNumber = [num2str(rand(1)) '\n'];
  7.     % Write number to file
  8.     fprintf(fid, randNumber);
  9. end
  10. % Close file
  11. fclose(fid);
  12. % Quit MATLAB
  13. quit force
复制代码

Noticethe last line of this file. The 'Quit' command is necessary toterminate MATLAB when we're finished.

The PHP file
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:

  1. <html>
  2.     <body>
  3.         <form action="" method="post">
  4.             Enter a filename <input type="text" name="filepath"><br />
  5.             <input type="submit" /><br />
  6.         </form>
  7.     </body>
  8. </html>

  9. <?php
  10. if(isset($_POST['filepath'])) {
  11.     $filename  = $_POST['filepath'];
  12.     $inputDir  = "C:\\output";
  13.     $outputDir = "C:\\output";
  14.     $command = "matlab -sd ".$inputDir." -r phpcreatefile('".$outputDir."\".$filename."')";
  15.     exec($command);
  16.     echo "The following command was run: ".$command."<br/>";
  17.     echo $filename." was created in ".$outputDir."<br/>";
  18. }
  19. ?>
复制代码

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.

    1. $filename= the filename submitted by the user from our form
    2. $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)
    3. $outpurDir= the path to the folder we are going to create our text file in
    4. $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.
    5. exec($command)executes our command line string as if you'd entered it in thecommand window
    6. 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.

Notes
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.
 楼主| 发表于 2012-10-18 06:53 | 显示全部楼层
出现的问题:                                                                                                                                                                                                                                                                                  
/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
ThreadSubject: error message " no display specified"

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,
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

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>,
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 Pater
 楼主| 发表于 2012-10-18 06:56 | 显示全部楼层
CallingMATLAB from PHP
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:
      1. 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:
  1. sudo-H licenseduser command
复制代码
The-H is necessary for the HOME environment variables to be changedto the target user.
      2. 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
  1. sudovisudo
复制代码
Thenadd the following line:
  1. apache-userALL=NOPASSWD: /usr/local/bin/matlab
复制代码
3. Nowyou should craft your exec() call in PHP. The basic syntax forstarting a MATLAB process in the backgroundis:
  1. /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:
  1. $command= "sudo -H licenseduser /usr/local/bin/matlab -r"command;exit;"
复制代码
4. Additionally,if you want to be able to save graphics, I found it necessary toprepend the command with:
  1. 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).
Pleasenote that there are security issues in giving sudo privileges toyour apache/webserver user, especially with NOPASSWD.
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-11-15 22:48 , Processed in 0.085213 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表