版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 消防知識題庫及答案
- 消防安全題目及答案
- 服裝店服務(wù)標(biāo)準(zhǔn)操作手冊
- 醫(yī)院感染防控操作流程手冊
- 空調(diào)器壓縮機(jī)裝配工春節(jié)假期安全告知書
- 酒店餐飲菜品制作與質(zhì)量控制手冊
- 倉儲企業(yè)安全生產(chǎn)責(zé)任制管理制度
- 2025年寵物護(hù)理美容專業(yè)資格考試試題及答案解析
- 2025年護(hù)理三基三嚴(yán)習(xí)題(附答案)
- A15-附件1-1交工驗(yàn)收前質(zhì)量檢測方案
- 《超純水制備培訓(xùn)資料》課件
- 定制手機(jī)采購合同協(xié)議
- CNAS-CL05-2009 實(shí)驗(yàn)室生物安全認(rèn)可準(zhǔn)則
- 2024-2025學(xué)年湖北省新高考聯(lián)考協(xié)作體高一上學(xué)期12月聯(lián)考生物B及答案
- 攻擊面管理技術(shù)應(yīng)用指南 2024
- 電梯井道腳手架搭設(shè)方案
- DL∕T 622-2012 立式水輪發(fā)電機(jī)彈性金屬塑料推力軸瓦技術(shù)條件
- 傳染病學(xué)-病毒性肝炎
- 重慶市沙坪壩小學(xué)小學(xué)語文五年級上冊期末試卷
- 陶瓷巖板應(yīng)用技術(shù)規(guī)程
- 中藥制劑技術(shù)中職PPT完整全套教學(xué)課件
評論
0/150
提交評論