Read and Write MAT Files and Call MATLAB from Within R 读取和写入 MAT 文件并从 R 内调用 MATLAB_第1页
Read and Write MAT Files and Call MATLAB from Within R 读取和写入 MAT 文件并从 R 内调用 MATLAB_第2页
Read and Write MAT Files and Call MATLAB from Within R 读取和写入 MAT 文件并从 R 内调用 MATLAB_第3页
Read and Write MAT Files and Call MATLAB from Within R 读取和写入 MAT 文件并从 R 内调用 MATLAB_第4页
Read and Write MAT Files and Call MATLAB from Within R 读取和写入 MAT 文件并从 R 内调用 MATLAB_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Package‘R.matlab’

October12,2022

Version3.7.0

DependsR(>=2.14.0)

Importsmethods,utils,R.methodsS3(>=1.7.1),R.oo(>=1.23.0),R.utils(>=2.5.0)

SuggestsMatrix,SparseM

TitleReadandWriteMATFilesandCallMATLABfromWithinR

AuthorHenrikBengtsson[aut,cre,cph],

AndyJacobson[ctb](InternalMATv4reader),

JasonRiedy[ctb](Supportforreadingcompressedfiles,sparsematricesandUTF-encodedstrings.)

MaintainerHenrikBengtsson

<henrikb@>

DescriptionMethodsreadMat()andwriteMat()forreadingandwrit-

ingMATfiles.ForuserwithMATLABv6ornewerinstalled(eitherlocallyoronare-motehost),thepackagealsoprovidesmethodsforcontrollingMATLAB(trade-

mark)viaRandsendingandretrievingdatabetweenRandMATLAB.

LicenseLGPL(>=2.1)LazyLoadTRUEByteCompileTRUE

URL

/HenrikBengtsson/R.matlab

BugReports

/HenrikBengtsson/R.matlab/issues

NeedsCompilationno

RepositoryCRAN

Date/Publication2022-08-2521:52:34UTC

Rtopicsdocumented:

R.matlab-package

2

TheMATLABserverrunninginMATLAB

5

Matlab

16

readMat

23

writeMat

26

1

2 R.matlab-package

Index

29

matlab-package PackageR.matlab

Description

MethodsreadMat()andwriteMat()forreadingandwritingMATfiles.ForuserwithMATLABv6ornewerinstalled(eitherlocallyoronaremotehost),thepackagealsoprovidesmethodsforcontrollingMATLAB(trademark)viaRandsendingandretrievingdatabetweenRandMATLAB.

Inbrief,thispackageprovidesaone-directionalinterfacefromRtoMATLAB,withcommunicationtakingplaceviaaTCP/IPconnectionandwithdatatransferredeitherthroughanotherconnectionorviathefilesystem.OntheMATLABside,theTCP/IPconnectionishandledbyasmallJavaadd-on.

ThemethodsforreadingandwritingMATfilesarestable.TheRtoMATLABinterface,thatistheMatlabclass,islessprioritizedandshouldbeconsideredabetaversion.

Forpackagehistory,seeshowHistory(R.matlab).

Requirements

Thisisacross-platformpackageimplementedinplainR.ThispackagedependsontheR.oopack-age[1].

TousetheMatlabclassorrequestingverboseoutputmessages,the

R.utils

packageisloadedwhenneeded(andthereforerequiredinthosecases).

ThereadMat()andwriteMat()methodsdonotrequireaMATLABinstallationneitherdotheydependonthe

Matlab

class.

ToconnecttoMATLAB,MATLABv6orhigherisrequired.ItdoesnotworkwithMATLABv5orbefore(becausethoseversionsdonotsupportJava).ForconfirmedMATLABversions,seethe

Matlab

class.

Installation

Toinstallthispackagedo

install.packages("R.matlab")

Togetstarted

Togetstarted,see:

readMat

()and

writeMat

()-ForreadingandwritingMATfiles(MATLABisnotneeded).

Matlab

-TostartMATLABandcommunicatewithitfromR.

R.matlab-package 3

Miscellaneous

ArelatedinitiativeisRMatlabbyDuncanTempleLangandOmegahat.Itprovidesabi-directionalinterfacebetweentheRandMATLABlanguages.Formoredetails,see

https://www.omegahat.

net/RMatlab/

.TocallRfromMATLABonWindows(only),seeMATLABR-linkbyRobertHen-

sonavailableattheMATLABCentralFileExchange(

/matlabcentral/

fileexchange/5051-matlab-r-link

).

Howtocitethispackage

Wheneverusingthispackage,pleaseciteas

TroubleshootingIngeneral:

Fortroubleshootingingeneral,rerunerroneousfunctionwithverbose/debugmessagesturnedon.

ForreadMat()andwriteMat()seetheirhelp.ForcommunicationwithaMATLABserver,use

matlab<-Matlab()setVerbose(matlab,threshold=-2)

Thelowerthethresholdisthemoreinformationyouwillsee.

CannotconnecttoMATLAB:

IfRfailstoconnecttoMATLAB,makesuretotrytheexampleinhelp(Matlab)first.MakesurethattheMATLABserverisrunningbeforetryingtoconnecttoitfromRfirst.IfMATLABisrunningbutopen()timesout,makesureMATLABislisteningtothesameportthatRistryingtoconnectto.Ifthatdoesnothelp,trytoincreasethetime-outlimit,seehelp(open.Matlab).

Expectedan’answer’fromMATLAB,butkeptreceivingnothing.:

WhenlaunchingareallylongMATLABprocessbyevaluate(),youmaygettheaboveerrormessage.

Reason:Thishappensbecauseevaluate()expectareplyfromMATLABassoonasMATLABisdone.Thewaitingshouldbe"blocked",i.e.itshouldwaituntilitreceivessomething.Forunknownreasons,thisisnotalwayshappening.TheworkaroundwehaveimplementedistotryreadResult/maxTrieswaitingreadResult/intervalsecondsin-between.

Solution:Increasethetotalwaitingtimebysettingtheaboveoptions,e.g.

setOption(matlab,"readResult/interval",10) #Defaultis1secondsetOption(matlab,"readResult/maxTries",30*(60/10))#~30minutes

4 R.matlab-package

Wishlist

Hereisalistoffeaturesthatwouldbeuseful,butwhichIhavetoolittletimetoaddmyself.Con-tributionsareappreciated.

Addafunction,say,Matlab$createShortcut()whichcreatesaWindowsshortcuttostarttheMATLABserverbydoubleclickingit.ItshouldbepossibletocreateitinthecurrentdirectoryortotheDesktop.MaybeitispossibletodothisuponinstallationandeventoaStart->AllPrograms->Rmenu.

Toimprovesecurity,updatetheMatlabServer.mscripttoallowtheusertospecifya"pass-word"tobesenduponconnectionfromRinorderforMATLABtoaccepttheconnection.ThispasswordshouldbepossibletospecifyfromthecommandlinewhenstartingMATLAB.Ifnotgiven,nopasswordisrequired.

AddadditionalmethodstotheMatlabclass.Forinstance,inlinefunctioninMATLABcouldhaveitsownmethod.

WrapupcommonMATLABcommandsasmethodsoftheMatlabclass,e.g.who(matlab),clear(matlab)etc.Canthisbedoneautomaticallyusing"reflection",sothatrequiredargu-mentsareautomaticallydetected?

AddaccesstoMATLABvariablesvia"$"and"$<-",e.g.matlab$Aandmatlab$A<-1234.Isthiswanted?Maybethesameforfunctions,e.g.matlab$dice(1000).Isitpossibletoreturnmultiplereturnvalues?

Ifyouconsiderimplementsomeoftheabove,makesureitisnotalreadyimplementedbydown-loadingthelatest"devel"version!

Acknowledgments

Thankstothefollowingpeoplewhocontributedwithvaluablefeedback,suggestions,codeandmore:

PatrickDrechsler,Biocenter,UniversityofWuerzburg.

SpencerGraves.

AndyJacobson,AtmosphericandOceanicSciencesProgram,PrincetonUniversity.

JasonRiedy,ComputerScienceDivision,UniversityofCalifornia,Berkeley.

ChrisSims,DepartmentofEconomics,PrincetonUniversity.

FrankStephen,NationalRenewableEnergyLaboratory.

YichunWei,DepartmentofBiologicalSciences,UniversityofSouthernCalifornia.

WangYu,ECEDepartment,IowaStateUniversity.

License

ThereleasesofthispackageislicensedunderLGPLversion2.1ornewer.

Thedevelopmentcodeofthepackagesisunderaprivatelicense(whereapplicable)andpatchessenttotheauthorfallunderthelatterlicense,butwillbe,ifincorporated,releasedunderthe"release"licenseabove.

1.TheMATLABserverrunninginMATLAB

PAGE

11

PAGE

10

1.TheMATLABserverrunninginMATLAB

References

1H.Bengtsson,TheR.oopackage-Object-OrientedProgrammingwithReferencesUsingStandardRCode,InKurtHornik,FriedrichLeischandAchimZeileis,editors,Proceedingsofthe3rdInterna-tionalWorkshoponDistributedStatisticalComputing(DSC2003),March20-22,Vienna,Austria.

/conferences/DSC-2003/Proceedings/

Author(s)

HenrikBengtsson

TheMATLABserverrunninginMATLAB

TheMATLABserverrunninginMATLAB

Description

ThissectiongivesadditiondetailsontheMATLABserver.Attheend,theMatlabServer.mscriptandtheInputStreamByteWrapper.javacodeisshown.

StartingtheMATLABserveronWindows

Notethatyou"cannotpreventMATLABfromcreatingawindowwhenstartingonWindowssys-tems,butyoucanforcethewindowtobehidden,byusing"theoption-minimize.See

https:

///matlabcentral/answers/102082

formoreinformation.

MatlabServer.mscript

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%MatlabServer

%

%ThisscriptsstartsaminimalisticMATLAB"server".

%

%Whenstarted,theserverlistensforconnectionsatport9999orthe

%portnumberspecifiedbytheenvironmentvariable'MATLABSERVER_PORT'.

%

%Troubleshooting:Ifnotworkingoutofthebox,addthiswilltothe

%MATLABpath.MakesureInputStreamByteWrapper.classisinthesame

%directoryasthisfile!

%

%Requirements:

%ThisrequiresMATLABwithJavasupport,i.e.MATLABv6orhigher.

%

%Author:HenrikBengtsson,2002-2016

%

%References:

%[1]

/access/helpdesk/help/techdoc/

% matlab_external/ch_jav34.shtml#49439

%[2]

http://staff.science.uva.nl/~horus/dox/horus2.0/user/

% html/n_installUnix.html

%[3]

/access/helpdesk/help/toolbox/

% modelsim/a1057689278b4.html

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fprintf(2,'RunningMatlabServerv3.5.9-9000\n');

%addpathR/R_LIBS/linux/library/R.matlab/misc/

%------------------------------------

%MATLABversion-dependentsetup

%------------------------------------

%IdentifymajorversionofMatlab

MatlabServer_tmp_hasMajor=eval('length(regexp(version,''^[0-9]''))~=0','0');if(MatlabServer_tmp_hasMajor)

MatlabServer_tmp_verParts=sscanf(version,'%d.');MatlabServer_tmp_verMajor=MatlabServer_tmp_verParts(1);clearMatlabServer_tmp_verParts;

else

MatlabServer_tmp_verMajor=-1;end

clearMatlabServer_tmp_hasMajor;

if(MatlabServer_tmp_verMajor<6)

%Javaisnotavailable/supported

error('MATLABv5.xandbelowisnotsupported.');elseif(MatlabServer_tmp_verMajor==6)

fprintf(2,'MATLABv6.xdetected.\n');

%DefaultsaveoptionMatlabServer_saveOption='';

%InMATLABv6onlythestaticJavaCLASSPATHissupported.Itis

%specifiedbya'classpath.txt'file.Thedefaultonecanbefound

%bywhich('classpath.txt').Ifa'classpath.txt'existsinthe

%current(!)directory(thatMATLABisstartedfrom),it*replaces*

%theglobalone.Thus,itisnotpossibletoaddadditionalpaths;

%theglobaloneshastobecopiedtothelocal'classpath.txt'file.

%

%TodotheaboveautomaticallyfromR,doesnotseemtobeanoption.else

fprintf(2,'MATLABv7.xorhigherdetected.\n');

%MATLABv7andabovesavescompressedfiles,whichisnotrecognized

%byR.matlab'sreadMat();forcesavinginoldformat.MatlabServer_saveOption='-V6';

fprintf(2,'Savingwithoption-V6.\n');

%InMATLABv7andabovebothstaticanddynamicJavaCLASSPATH:sexist.

%Usingdynamicones,itispossibletoaddthefile

%InputStreamByteWrapper.classtoCLASSPATH,givenitis

%inthesamedirectoryasthisscript.javaaddpath({fileparts(which('MatlabServer'))});

fprintf(2,'AddedInputStreamByteWrappertodynamicJavaCLASSPATH.\n');end

clearMatlabServer_tmp_verMajor;

%------------------------------------

%ImportJavaclasses

%------------------------------------

importjava.io.*;import.*;

%------------------------------------

%IfanoldMATLABserverisrunning,closeit

%------------------------------------

%Ifaserverobjectexistsfromapreviousrun,closeit.if(exist('MatlabServer_server'))

close(MatlabServer_server);clearMatlabServer_server;

end

%Ifaninputstreamexistsfromapreviousrun,closeit.if(exist('MatlabServer_is'))

close(MatlabServer_is);clearMatlabServer_is;

end

%Ifanoutputstreamexistsfromapreviousrun,closeit.if(exist('MatlabServer_os'))

close(MatlabServer_os);clearMatlabServer_os;

end

fprintf(2,' \n');

fprintf(2,'MATLABserverstarted!\n');fprintf(2,' \n');

fprintf(2,'MATLABworkingdirectory:%s\n',pwd);

%------------------------------------

%Initiateserversockettowhichclientsmayconnect

%------------------------------------

MatlabServer_port=getenv('MATLABSERVER_PORT');

if(length(MatlabServer_port)>0)MatlabServer_port=str2num(MatlabServer_port);

else

%Trytoopenaserversocketonport9999MatlabServer_port=9999;

end

%Ports1-1023arereservedfortheInternetAssignedNumbersAuthority.

%Ports49152-65535aredynamicportsfortheOS.[3]

if(MatlabServer_port<1023|MatlabServer_port>65535)

error('Cannotnotopenconnection.Port(''MATLABSERVER_PORT'')isoutofrange[1023,65535]:%d',end

fprintf(2,'Tryingtoopenserversocket(port%d)...',MatlabServer_port);MatlabServer_server=.ServerSocket(MatlabServer_port);

fprintf(2,'done.\n');

%------------------------------------

%Waitforclienttoconnect

%------------------------------------

%CreateasocketobjectfromtheServerSockettolistenandaccept

%connections.

%Openinputandoutputstreams

%Waitfortheclienttoconnect

fprintf(2,'Waitingforclienttoconnect(port%d)...',MatlabServer_port);MatlabServer_clientSocket=accept(MatlabServer_server);

fprintf(2,'connected.\n');

%...clientconnected.

MatlabServer_is=java.io.DataInputStream(getInputStream(MatlabServer_clientSocket));MatlabServer_os=java.io.DataOutputStream(getOutputStream(MatlabServer_clientSocket));

%------------------------------------

%TheMATLABserverstatemachine

%------------------------------------

%Commands

MatlabServer_commands={'eval','send','receive','send-remote','receive-remote','echo','evalc'};

MatlabServer_lasterr=[];MatlabServer_variables=[];

%Aslongaswereceivedata,echothatdatabacktotheclient.MatlabServer_state=0;

while(MatlabServer_state>=0),

if(MatlabServer_state==0)

MatlabServer_tmp_cmd=readByte(MatlabServer_is);fprintf(2,'Receivedcmd:%d\n',MatlabServer_tmp_cmd);

if(MatlabServer_tmp_cmd<-1|MatlabServer_tmp_cmd>length(MatlabServer_commands))fprintf(2,'Unknowncommandcode:%d\n',MatlabServer_tmp_cmd);

else

MatlabServer_state=MatlabServer_tmp_cmd;end

clearMatlabServer_tmp_cmd;

%

%'evalc'

%

elseif(MatlabServer_state==strmatch('evalc',MatlabServer_commands,'exact'))MatlabServer_tmp_bfr=char(readUTF(MatlabServer_is));

fprintf(2,'"evalc"string:"%s"\n',MatlabServer_tmp_bfr);try

MatlabServer_tmp_bfr=sprintf(MatlabServer_tmp_bfr);MatlabServer_tmp_result=evalc(MatlabServer_tmp_bfr);writeByte(MatlabServer_os,0);

fprintf(2,'Sentbyte:%d\n',0);writeUTF(MatlabServer_os,MatlabServer_tmp_result);fprintf(2,'SentUTF:%s\n',MatlabServer_tmp_result);flush(MatlabServer_os);

clearMatlabServer_tmp_result;catch

MatlabServer_lasterr=sprintf('Failedtoevaluateexpression''%s''.',MatlabServer_tmp_bfr);fprintf(2,'EvaluationException:%s\n',MatlabServer_lasterr);

writeByte(MatlabServer_os,-1);fprintf(2,'Sentbyte:%d\n',-1);

writeUTF(MatlabServer_os,MatlabServer_lasterr);fprintf(2,'SentUTF:%s\n',MatlabServer_lasterr);flush(MatlabServer_os);

endflush(MatlabServer_os);MatlabServer_state=0;

clearMatlabServer_tmp_bfr;

%

%'eval'

%

elseif(MatlabServer_state==strmatch('eval',MatlabServer_commands,'exact'))MatlabServer_tmp_bfr=char(readUTF(MatlabServer_is));

fprintf(2,'"eval"string:"%s"\n',MatlabServer_tmp_bfr);try

eval(MatlabServer_tmp_bfr);writeByte(MatlabServer_os,0);fprintf(2,'Sentbyte:%d\n',0);

flush(MatlabServer_os);catch

MatlabServer_lasterr=sprintf('Failedtoevaluateexpression''%s''.',MatlabServer_tmp_bfr);fprintf(2,'EvaluationException:%s\n',MatlabServer_lasterr);

writeByte(MatlabServer_os,-1);fprintf(2,'Sentbyte:%d\n',-1);

writeUTF(MatlabServer_os,MatlabServer_lasterr);fprintf(2,'SentUTF:%s\n',MatlabServer_lasterr);flush(MatlabServer_os);

endflush(MatlabServer_os);MatlabServer_state=0;

clearMatlabServer_tmp_bfr;

%

%'send'

%

elseif(MatlabServer_state==strmatch('send',MatlabServer_commands,'exact'))MatlabServer_tmp_tmpname=sprintf('%s_%d.mat',tempname,MatlabServer_port);MatlabServer_tmp_expr=sprintf('save(MatlabServer_tmp_tmpname,''%s''',MatlabServer_saveOption);

MatlabServer_tmp_ok=1;

forMatlabServer_tmp_k=1:length(MatlabServer_variables),MatlabServer_tmp_variable=MatlabServer_variables{MatlabServer_tmp_k};if(exist(MatlabServer_tmp_variable)~=1)

MatlabServer_lasterr=sprintf('Variable''%s''notfound.',MatlabServer_tmp_variable);fprintf(2,'%s\n',MatlabServer_lasterr);

MatlabServer_tmp_ok=0;break;

end;

MatlabServer_tmp_expr=sprintf('%s,''%s''',MatlabServer_tmp_expr,MatlabServer_tmp_variable);end;

MatlabServer_tmp_expr=sprintf('%s)',MatlabServer_tmp_expr);if(~MatlabServer_tmp_ok)

writeInt(MatlabServer_os,-1);writeUTF(MatlabServer_os,MatlabServer_lasterr);

else

fprintf(2,'%s\n',MatlabServer_tmp_expr);eval(MatlabServer_tmp_expr);

writeInt(MatlabServer_os,0);%Hereanythingbut-1means"success"writeUTF(MatlabServer_os,MatlabServer_tmp_tmpname);

end

MatlabServer_tmp_answer=readByte(MatlabServer_is);fprintf(2,'answer=%d\n',MatlabServer_tmp_answer);

MatlabServer_state=0;

clearMatlabServer_tmp_nameMatlabServer_tmp_exprMatlabServer_tmp_okMatlabServer_tmp_answer;

%

%'send-remote'

%

elseif(MatlabServer_state==strmatch('send-remote',MatlabServer_commands,'exact'))MatlabServer_tmp_tmpname=sprintf('%s_%d.mat',tempname,MatlabServer_port);MatlabServer_tmp_expr=sprintf('save(MatlabServer_tmp_tmpname,''%s''',MatlabServer_saveOption);

MatlabServer_tmp_ok=1;

forMatlabServer_tmp_k=1:length(MatlabServer_variables),MatlabServer_tmp_variable=MatlabServer_variables{MatlabServer_tmp_k};if(exist(MatlabServer_tmp_variable)~=1)

MatlabServer_lasterr=sprintf('Variable''%s''notfound.',MatlabServer_tmp_variable);fprintf(2,'%s\n',MatlabServer_lasterr);

MatlabServer_tmp_ok=0;break;

end;

MatlabServer_tmp_expr=sprintf('%s,''%s''',MatlabServer_tmp_expr,MatlabServer_tmp_variable);end;

clearMatlabServer_tmp_kMatlabServer_tmp_variable;

MatlabServer_tmp_expr=sprintf('%s)',MatlabServer_tmp_expr);if(~MatlabServer_tmp_ok)

writeInt(MatlabServer_os,-1);writeUTF(MatlabServer_os,MatlabServer_lasterr);

else

fprintf(2,'%s\n',MatlabServer_tmp_expr);eval(MatlabServer_tmp_expr);

MatlabServer_tmp_file=java.io.File(MatlabServer_tmp_tmpname);MatlabServer_tmp_maxLength=length(MatlabServer_tmp_file);clearMatlabServer_tmp_file;

writeInt(MatlabServer_os,MatlabServer_tmp_maxLength);%Hereanythingbut-1means"success"fprintf(2,'Sendint:%d(maxLength)\n',MatlabServer_tmp_maxLength);MatlabServer_tmp_fid=fopen(MatlabServer_tmp_tmpname,'r');

MatlabServer_tmp_count=1;

while(MatlabServer_tmp_count~=0)

[MatlabServer_tmp_bfr,MatlabServer_tmp_count]=fread(MatlabServer_tmp_fid,65536,'int8');if(MatlabServer_tmp_count>0)

write(MatlabServer_os,MatlabServer_tmp_bfr);end;

end;fclose(MatlabServer_tmp_fid);

fprintf(2,'Sendbuffer:%dbytes.\n',MatlabServer_tmp_maxLength);delete(MatlabServer_tmp_tmpname);

clearMatlabServer_tmp_bfrMatlabServer_tmp_countMatlabServer_tmp_maxLengthMatlabServer_tmp_fiend

flush(MatlabServer_os);

MatlabServer_tmp_answer=readByte(MatlabServer_is);

fprintf(2,'answer=%d\n',MatlabServer_tmp_answer);

MatlabServer_state=0;

clearMatlabServer_tmp_nameMatlabServer_tmp_exprMatlabServer_tmp_okMatlabServer_tmp_answer;

%

%'receive-remote'

%

elseif(MatlabServer_state==strmatch('receive-remote',MatlabServer_commands,'exact'))MatlabServer_tmp_len=readInt(MatlabServer_is);

fprintf(2,'WillreadMATfilestructureoflength:%dbytes.\n',MatlabServer_tmp_len);

MatlabServer_tmp_reader=InputStreamByteWrapper(4096);MatlabServer_tmp_bfr=[];

MatlabServer_tmp_count=1;

while(MatlabServer_tmp_len>0&MatlabServer_tmp_count>0)

MatlabServer_tmp_count=MatlabServer_tmp_reader.read(MatlabServer_is,min(4096,MatlabServer_tmif(MatlabServer_tmp_count>0)

MatlabServer_tmp_bfr=[MatlabServer_tmp_bfr;MatlabServer_tmp_reader.bfr(1:MatlabServer_tmp_coMatlabServer_tmp_len=MatlabServer_tmp_len-MatlabServer_tmp_count;

end;end;

clearMatlabServer_tmp_readerMatlabServer_tmp_countMatlabServer_tmp_len;

MatlabServer_tmp_tmpfile=sprintf('%s_%d.mat',tempname,MatlabServer_port);MatlabServer_tmp_fh=fopen(MatlabServer_tmp_tmpfile,'wb');fwrite(MatlabServer_tmp_fh,MatlabServer_tmp_bfr,'int8');fclose(MatlabServer_tmp_fh);

clearMatlabServer_tmp_fhMatlabServer_tmp_bfr;load(MatlabServer_tmp_tmpfile);delete(MatlabServer_tmp_tmpfile);

clearMatlabServer_tmp_tmpfile;

writeByte(MatlabServer_os,0);

MatlabServer_state=0;

%

%'receive'

%

elseif(MatlabServer_state==strmatch('receive',MatlabServer_commands,'exact'))MatlabServer_tmp_filename=char(readUTF(MatlabServer_is));

fprintf(2,'WillreadMATfile:"%s"\n',MatlabServer_tmp_filename);load(MatlabServer_tmp_filename);

clearMatlabServer_tmp_filename;

writeByte(MatlabServer_os,0);

MatlabServer_state=0;

clearMatlabServer_tmp_filename;end

end

%------------------------------------

%ShuttingdowntheMATLABserver

%------------------------------------

fprintf(2,' \n');

fprintf(2,'MATLABservershutdown!\n');fprintf(2,' \n');

writeByte(MatlabServer_os,0);close(MatlabServer_os);close(MatlabServer_is);close(MatlabServer_server);quit;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%HISTORY:

%2016-04-05[v3.6.0]

%oAllverbose/debugmessagesareoutputtedtostream#2("stderr").

%2015-09-11[v3.3.0]

%oNowtemporaryfilesuseformat<tempname>_<port>.mat.

%oAdd'MatlabServer_'prefixtoallvariables.

%oAdd'evalc'command.ThankstoRohanShahforthis.

%2015-01-08[v3.1.2]

%oBUGFIX:Matlab$getVariable()foranon-existingvariablewould

% crashtheR-to-Matlabcommunicationifremote=FALSE.

%2014-06-23[v3.0.2]

%oROBUSTNESS:Variables'lasterr'and'variables'arenowalways

% defined.PotentialbugspottedbyStevenJaffeatMorganStanley.

%oAddedmoreprogress/verboseoutput,e.g.currentworkingdirectory.

%2014-01-21[v2.2.0]

%oBUGFIX:TheMatlabServer.mscriptwouldincorrectlyconsider

% Matlabv8andaboveasMatlabv6.ThankstoFrankStephenatNREL

% forreportingonthisandprovidingapatch.

%2013-07-11[v1.3.5]

%oUpdatedmessagestouse'MATLAB'insteadof'Matlab'.

%2010-10-25[v1.3.4]

%oBUGFIX:TheMatlabServer.mscriptincorrectlyreferredtothe

% InputStreamByteWrapperclassasjava.io.InputStreamByteWrapper.

% ThanksKenvorCotheyatGMOLCCforreportingonthis.

%2010-08-28

%oNowtheMatlabServerscriptreportsitsversionwhenstarted.

%2010-08-27

%oBUGFIX:NowMatlabServer.msavesvariablesusingthefunctionform,

% i.e.save().Thissolvestheproblemofhavingsinglequotationmarks

% inthepathname.ThanksMichaelQ.FanatNCStateUniversityfor

% reportingthisproblem.

%2009-08-25

%oBUGFIX:Startedtogettheerror"Undefinedfunctionormethod

% 'ServerSocket'forinputargumentsoftype'double'.".Itseemslike

% import.*etcdoesnotwork.Aworkaroundistospecifythe

% fullpathforallJavaclasses,e.g..ServerSocket.

% ThanksNicolasStadlerforreportingthisissue.

%2006-12-28

%oExtendedtheacceptedrangeofportsfrom[1023,49151]to[1023,66535].

%2006-05-08

%oBUGFIX:Theerrormessagestringforreportingportoutofrange

% wasinvalidandgavetheerror'...Line:109Column:45")"expected,

% "identifier"found.'.ThanksAlexanderNervediforreportingthis.

%2006-01-21

%oNowanerroristhrownifportnumberisoutof(safe)range.

%oAddedoptiontospecifytheportnumberviathesystemenvironment

% variableMATLABSERVER_PORT,afterrequestbyWangYu,IowaStateUniv.

%2005-03-08

%oBUGFIX:substring()isnotrecognizedbyMATLABv7.Usingregexp()

% whichworksinMATLAB6.5and7.Workaroundeval('try','catch').

% ThanksPatrickDrechsler,UniversityofWuerzburgforthebugreport.

%2005-02-24

%oNowthedynamicJavaclasspathissetforMATLABv7orhigher.This

% willsimplifylifeforMATLABv7users.

%2005-02-22

%oAddedjavaaddpath()toincludeInputStreamByteWrapper.class.

% ThanksYichunWeiforfeedbackandgreatsuggestions.

%2005-02-11

%oIfMATLABv7orhigherisdetected,allMATstructuresaresavedwith

% option'-V6'soreadMat()inR.matlabcanreadthem.

%2002-09-02[ormaybealittlebitearlier]

%oCreated.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

InputStreamByteWrapper.(class|java)script

TheJavaclassInputStreamByteWrapperisneededinorderforMATLABtoreceivedataviaadatastream.Rsendsdataviaadatastreamif,andonlyif,theconnectionwassetupfor"remote"communication,thatis,withargumentremote=TRUE).

importjava.io.*;

/*********************************************************************

%CompilefromwithinMATLABwith:

%!javacInputStreamByteWrapper.java

%MATLABexamplethatreadsafileusingJavacodeandwritesit

%backtoatemporaryfileusingMATLABcode.Finallythecontents

%ofthenewfileisdisplayed.

reader=InputStreamByteWrapper;%Defaultbuffersizeis4096bytes.in=java.io.FileInputStream('InputStreamByteWrapper.java');

bfr=[];len=1;

while(len>0)

len=reader.read(in,16);%Read16bytesatthetime(offset=0).if(len>0)

bfr=[bfr;reader.bfr(1:len)];%AddbytestomyMATLABbuffer.end

end

close(in);

clearin,reader;disp(bfr');

tmpfile=tempname;

fh=fopen(tmpfile,'wb');fwrite(fh,bfr,'char');fclose(fh);

type(tmpfile);

*********************************************************************/publicclassInputStreamByteWrapper{

publicstaticbyte[]bfr=null;

publicInputStreamByteWrapper(intcapasity){bfr=newbyte[capasity];

}

publicInputStreamByteWrapper(){this(4096);

}

publicintread(InputStreamin,intoffset,intlength)throwsIOException{returnin.read(bfr,offset,length);

}

publicintread(InputStreamin,intlength)throwsIOException{

PAGE

16

Matlab

Matlab

PAGE

17

returnread(in,0,length);

}

publicintread(InputStreamin)throwsIOException{returnin.read(bfr);

}

}

/*********************************************************************HISTORY:

2013-07-11

Updatedcommentstouse'MATLAB'insteadof'Matlab'.2002-09-02[ormaybealittlebitearlier]

Created.

*********************************************************************/

Matlab MATLABclientforremoteorlocalMATLABaccess

Description

Package:R.matlab

ClassMatlab

Object

~~|

~~+--Matlab

Directlyknownsubclasses:

publicstaticclassMatlab

extends

Object

Usage

Matlab(host="localhost",port=9999

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论