当前位置: 代码迷 >> PHP >> 施用php在网页执行matlab
  详细解决方案

施用php在网页执行matlab

热度:46   发布时间:2016-04-28 23:48:49.0
使用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图像,不解。

<html>    <body>        <form action="" method="post">            输入命令: <input type="text" name="cmd">                  <input type="submit" /><br />        </form>    </body></html><?phpphpinfo();if(isset($_POST['cmd'])){$cmd = $_POST['cmd'];$command="/usr/local/MATLAB/R2012a/bin/matlab -nodisplay -nosplash -r "."\"".$cmd."\"";//echo $command."<br/>";//$command="/usr/local/MATLAB/R2012a/bin/matlab -r "."\"".$cmd."\"";shell_exec("unset DISPLAY");//删除DISPLAY环境变量$out = shell_exec($command);$str="< 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, type one of these: helpwin, helpdesk, or demo.For product information, visit www.mathworks.com.";$out=ltrim($out,$str);$out=rtrim($out,">>");echo $out;}?>

相关截图:                                                                                                                                                                                                                                                                                            

输入sin(1:10)进行简单计算


输入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.

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:

  1. Right-clickthe shortcut icon for MATLAB  andselect Properties from the context menu. TheProperties dialog box for MATLAB opens to the Shortcut pane.

  2. 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"

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? 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/mytools
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 matlab(Windows) referencepage or the matlab(UNIX) referencepage.

Platform

Option

Description

All

-clicensefile

Set LM_LICENSE_FILE to licensefile.It can have the form [email protected].

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

  1. Createa Perl script such as

     #!/usr/local/bin/perl $val = 10;  system('matlab -r "test(' . ${val} . ')"');
  2. 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.


===============================================================================================================================

http://narnia.cs.ttu.edu/drupal/node/41

RunningMATLAB without graphic interface

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

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

#!/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

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


===============================================================================================================================

Linux下后台运行matlab   

命令如下:

nohupmatlab <name.m> name.out &
其中name.m是你自己的M文件.
更完整的写法应该是:
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:

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

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

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

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:

<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/>";}?>

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.



===============================================================================================================================

出现的问题:                                                                                                                                                                                                                                                                                  

/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: [email protected](Walter Roberson)

Date: 4Mar, 2008 20:07:35

Message: 2of 2

Replyto this message

Addauthor to My Watch List

Vieworiginal format

Flagas spam


Inarticle <[email protected]>,
PeterJohansson <[email protected]> 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

===============================================================================================================================

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:

    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
    sudovisudo
    Thenadd the following line:
    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: 
    /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;"

  4. Additionally,if you want to be able to save graphics, I found it necessary toprepend the command with: 
    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.




  相关解决方案