Home

LiveLink for MATLAB User's Guide

image

Contents

1. The first time COMSOL with MATLAB is started login and password information is requested to establish the client server connection The information is then saved in the user preference file and is not requested again Noe Ifyou want to reset the login information add the flag login force to the icon target path on Windows For Mac OS X and Linux operating systems enter the command comsol server matlab login force at a system command prompt Connecting the COMSOL Server and MATLAB Manually Manually connecting MATLAB to a COMSOL server can be useful if you need to start a MATLAB standalone and then connect to a COMSOL server or if you need to connect MATLAB and a COMSOL server running on different computers To manually connect MATLAB to a COMSOL server you need first to start MATLAB and a COMSOL server Starting a COMSOL Server e On Windows go to the start menu All Programs gt COMSOL 4 3a gt Client Server gt COMSOL Multiphysics 4 3a server On Mac OS X or Linux enter comsol server at a terminal window Connecting MATLAB to the COMSOL Server In MATLAB add the path of the COMSOL43a mli directory 2 Enter the command below at the MATLAB prompt mphstart lt portnumber gt Where lt portnumber gt is the port used by the COMSOL server If the COMSOL server is listening on the default port 2036 the port number does not need to be specified ADJUSTING THE MATLAB JAVA HEAP SIZE You may need to modify the M
2. data mphint2 model lt expr gt edim solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index You can also set the property solnum to end to evaluate the expression for the last inner solution By default the evaluation is done using the last inner solution e outersolnum specify the outer solution number for data evaluation Outer solutions are generated with parametric sweeps data mphint2 model lt expr gt edim outersolnum lt outersolnum gt 5 where lt outersolnum gt is a positive integer corresponding to the outer solution index The default settings use the first outer solution for the data evaluation e To evaluate the expression data at a specific time use the property t data mphint2 model lt expr gt edim t lt time gt where lt time gt is a double array The default value corresponds to all the stored time steps OUTPUT FORMAT The function mphint2 also supports other output format To extract the unit of the evaluated expression define an extra output variable data unit mphint2 model lt expr gt edim with unit is a 1xN cell array where N is the number of expressions to evaluate By default mphint2 returns the results as a squeezed singleton To get the full singleton set the squeeze property to off data mphint2 model lt expr gt edim squeeze off Set the property matrix to off to return the data as a cell array
3. mphgeom model 0 9F 0 8 F 0 7 F O6F 05F 0 4F 0 33f 0 2F 0 1F Create a loop that changes the position of the circle in increments for a 0 2 0 1 0 5 model param set a a geom1 run WORKING WITH GEOMETRY 45 end Create a mesh model mesh create meshi geom1 Add a Weak Form PDE interface w model physics create w WeakFormPDE geomi w feature wfeqi set weak 1 test ux ux test uy uy diri w feature create dir1 DirichletBoundary 1 dir1 selection set 1 2 3 6 7 srci w feature create src1 SourceTerm 2 srce1 set f 1 1 src1 selection set 3 Then create a stationary study step std1 model study create std1 stat std1 feature create stat1 Stationary Create a parametric sweep feature p1 model batch create p1 Parametric p1 set pname a p1 set plist range 0 2 0 1 0 8 pi1 run Alternatively you can run the parametric sweep using a MATLAB for loop for a 0 2 0 1 0 8 model param set a a std1 run end After updating a parameter that affects the geometry COMSOL detects EI this change and automatically updates the geometry and mesh before starting the solver The geometry is associative which means that physics Note settings are preserved as the geometry changes Images and Interpolation Data This section describes how to generate geometry from a set of data points b
4. mphstart ipaddress port comsolpath creates a connection with a COMSOL server using the specified IP address and port number using the comsolpath that is specified This is useful if mphstart cannot find the location of the COMSOL Multiphysics installation mphstart can be used to create a connection from within MATLAB when this is started without using the COMSOL with MATLAB option mphstart then sets up the necessary environment and connect to COMSOL Prior to calling mphstart it is necessary to set the path of mphstart m in the MATLAB path or to change the current directory in MATLAB for example using the cd command to the location of the mphstart m file A COMSOL server must be started prior to running mphstart CHAPTER 6 COMMAND REFERENCE mphstate Purpose Syntax Description Get state space matrices for dynamic system str mphstate model soltag Out SP str mphstate model soltag Out SP1 SP2 str mphstate model soltag out SP returns a MATLAB structure str containing the state space matrix SP assembled using the solver node soltag and accessible as str SP SP being taken from the Out property list str mphstate model soltag Out SP1 SP2 returns a MATLAB structure str containing the state space matrices SP1 SP2 assembled using the solver node soltag and accessible as str SP1and str SP2 SP1 and SP2 being taken from the Out property list The functio
5. plot3 data vertex 1 data vertex 2 data vertex 3 axis equal view 3 Get the element types information stats types Get the number of edge element note that the edge type is the first type in the list numedgeelem stats numelem 1 mphmesh CHAPTER 6 COMMAND REFERENCE mphmin Purpose Syntax Description Perform minimum of expressions v1 vn mphmin model e1 en edim v1 vn unit mphmin model e1 en edim v1 Vvn mphmin model e1 en edim evaluates the minimum of the string expressions e1 en and returns the result in N matrices v1 Vvn with M rows and P columns M is the number of inner solution and P the number of outer solution used for the evaluation edim defines the element dimension line surface volume or as an integer value v1 Vvn mphmin model e1 en edim also returns the units in a 1xN cell array The function mphmin accepts the following property value pairs TABLE 6 18 PROPERTY VALUE PAIRS FOR THE MPHMIN COMMAND PROPERTY PROPERTY VALUE DEFAULT DESCRIPTION Dataset String active Data set tag solution data set Matrix off on on Returns data as a matrix or as a cell Outersolnum Positive integer 1 Solution number for array parametric sweep Selection Integer vector all Selection list or named string all selection Solnum Integer vector all Solution for evaluation end all Squeeze
6. where lt ftag gt is the string defined when creating the operation EI For a property list available for the geometry features see Geometry in the x COMSOL Java API Reference Guide ote To build the geometry sequence enter model geom lt geomtag gt run Alternatively to build the geometry sequence up to a given feature ftag enter model geom lt geomtag gt run lt ftag gt Displaying the Geometry Use the function mphgeom to display the geometry in a MATLAB figure mphgeom model1 To specify the geometry to display enter mphgeom model lt geomtag gt When running mphgeom the geometry node is automatically built Set the build property to specify how the geometry node is supposed to be built before displaying it Enter mphgeom model lt geomtag gt build build where buildisa string with the value off current or the geometry feature tag lt ftag gt which respectively does not build the geometry off builds the geometry WORKING WITH GEOMETRY 33 up to the current feature current or builds the geometry up to the specified geometry feature node ftag Use the parent property to specify the axes handle where to display the plot mphgeom model lt geomtag gt parent lt axes gt The following property is also available to specify the vertex edge or face rendering edgecolor edgelabels edgelabelscolor edgemode facealpha facelabels facelabelscolor fa
7. 0 05 oO The Data Set Syntax Use Data Sets to make solutions and meshes available for visualization and data analysis You can create Solution Data Set Mesh Data Set or Visualization Data Set such as for instance Cut Plane or Edge Data Sets While Solution and Mesh Data Sets are self defined Visualization Data Sets always refer to an existing Solution Data Set See Data Sets in the section Commands Grouped by Function of the COMSOL Multiphysics Java API Reference Guide to get a list of the See Also available Data Sets All plots refer to data sets the solutions are always available as the default p data set Tip CHAPTER 3 To create a data set at the MATLAB prompt use the command BUILDING MODELS model result dataset create lt dsettag gt dsettype where dsettype is one of the available data set types e Defining Data Sets in the COMSOL Multiphysics User s Guide Use of Data Sets in the COMSOL Java API Reference Guide al See Also The Numerical Node Syntax Use the numerical node to perform numerical evaluation from within the COMSOL model Numerical operations such as computing averages integrations maximums or minimums of a given expression are available You can also perform point and global evaluations To create a numerical node enter model result numerical create lt numtag gt numtype where numtype is the type of operation to be performed by the node
8. CHAPTER 4 WORKING WITH MODELS y D C McA McB u Let Null be the PDE constraint null space matrix and wd a particular solution fulfilling the constraints The solution vector U for the PDE problem can then be written U Nullx ud u0 where u0 is the linearization point which is the solution stored in the sequence once the state space export feature is run EXTRACT STATE SPACE MATRICES The function mphstate requires that the input variables output variables and the list of the matrices to extract in the MATLAB workspace are all defined str mphstate model lt soltag gt input lt input gt output lt output gt out out where lt soltag gt is the solver node tag used to assemble the system matrices listed in the cell array out and lt input gt and lt output gt are cell arrays containing the list of the input and output variables respectively The output data str returned by mphstate is a MATLAB structure and the fields correspond to the assembled system matrices The input variables need to be defined as parameters in the COMSOL model The output variables are defined as domain point probes or global probes in the COMSOL model The system matrices that can be extracted with mphstate are listed in the table below EXPRESSION DESCRIPTION MA McA matrix MB McB matrix A A matrix B B matrix 0 C matrix D D matrix Mc Mc matrix Null Null matrix ud ud vector x0 x0 vector WORKING WITH
9. deviation or variance respectively When performing a minimum or maximum operation on the data series you can specify to perform the operation using the real or the absolute value Set the property minmaxobj to real or abs respectively data mphevalpoint model lt expr gt dataseries dataseries minmaxobj valuetype By default valuetype is real OUTPUT FORMAT The function mphevalpoint supports other output formats To extract the unit of the evaluated expression define an extra output variable data unit mphevalpoint model lt expr gt with unit is a 1xN cell array where N is the number of expressions to evaluate By default mphevalpoint returns the result s as a squeezed singleton To get the full singleton set the squeeze property to off data mphevalpoint model lt expr gt squeeze off Set the property matrix to off to return the data as a cell array instead of a double array CHAPTER 4 WORKING WITH MODELS data mphevalpoint model lt expr gt matrix off Evaluating an Integral Evaluate an integral of expression with the function mphint2 The function mphint is now obsolete and will be removed in a future l j version of the software If you are using this function in your code you Note can now replace it by mphint2 To evaluate the integral of the expression over the domain with the highest space domain dimension call the function mphint2 as in
10. integration Q mphint2 model ht ndflux 1 intsurface on CHAPTER 6 COMMAND REFERENCE mphint2 selection 2 3 4 See also mpheval mphevalpoint mphglobal mphinterp 221 mphinterp 222 CHAPTER 6 Purpose Syntax Description Evaluate expressions in arbitrary points or data sets v1 vn mphinterp model e1 en coord coord v1 vn mphinterp model e1 en dataset dsettag v1 vn unit mphinterp model e1 en v1 vn mphinterp model e1 en coord coord evaluates expressions e1 en at the coordinates specified in the double matrix coord Evaluation is supported only on Solution Data Sets v1 vn mphinterp model e1 en dataset dsettag evaluates expressions e1 en on the specified data set dsettag In this case the data set needs to be ofa type that defines an interpolation in itself such as cut planes revolve and so forth v1 vn unit mphinterp model e1 en returns in addition the unit of the expressions The function mphinterp accepts the following property value pairs TABLE 6 11 PROPERTY VALUE PAIRS FOR THE MPHINTERP COMMAND PROPERTY PROPERTY DEFAULT DESCRIPTION VALUE Complexfun off on on Use complex valued functions with real input Complexout off on off Return complex values Coord Double Coordinates for evaluation array Coorderr off on off Give an error
11. lt seltag gt where lt seltag gt is the tag ofa selection node to use for the data evaluation lt seltag gt can also be a positive integer array that corresponds to the domain index list The default selection is all domains where the expression is defined If the evaluation point does not belong to the specified domain selection the output value is NaN edim specify the element dimension for evaluation data mphinterp model lt expr gt coord lt coord gt edim edim where edimis either a string or a positive integer such as point 0 edge 1 boundary 2 or domain 3 The default settings correspond to the model geometry space dimension When using a lower space dimension value make sure that the evaluation point coordinates dimension has the same size ext specify extrapolation control value This ensures you return data for points that are outside the geometry data mphinterp model lt expr gt coord lt coord gt ext lt ext gt 5 where lt ext gt is a double value The default value is 0 1 solnun specify the inner solution number for data evaluation Inner solutions are generated for the following analysis types time domain frequency domain eigenvalue or stationary with continuation parameters data mphinterp model lt expr gt coord lt coord gt solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index lt solnum gt
12. Adjacent Selection Using the COMSOL API This command creates a selection node using adjacent geometric entities model selection create lt seltag gt Adjacent The geometric entity level needs to be specified with the command model selection lt seltag gt set edim where edim is an integer defining the space dimension value 3 for domains 2 for boundaries domains 1 for edges boundaries and 0 for points The Adjacent selection node only supports the Selection node as an input BUILDING MODELS model selection lt seltag gt set Adjacent and specify the ball radius lt ro gt with the command model selection lt seltag gt set input lt seltag gt where lt seltag gt is the tag of an existing Selection node Select the level of geometric entities to add in the selection with the command model selection lt seltag gt set outputdim edim where edim is an integer defining the space dimension value 3 for domains 2 for boundaries domains 1 for edges boundaries and 0 for points If there are multiple domains in the geometry to include in the interior and exterior selected geometric entities then enter model selection lt seltag gt set interior on model selection lt seltag gt set exterior on To exclude the interior exterior select geometric entities and set the respective property to off Adjacent Selection Using MPHGETAD An alternative to the COMSOL API is to use t
13. CHAPTER 3 model result create pg1 1 model result pg1 set data dseti model result pg1 feature create glob1 Global model result pg1 feature glob1 set expr mod1 u mphplot model pg1 Global State variable u 36 Defining Model Settings Using External Data File To use tabulated data from files in a model use the interpolation function available under the Global Definitions node or the Definitions node of the model To add an interpolation function to the manual enter model func create lt functag gt Interpolation The interpolation function is initially defined globally and is located in the Model Builder on the COMSOL Desktop under the Global Definitions node If you have several model nodes in your model and you want to attach it to the specified model node lt mode1 gt enter model func lt functag gt model lt model gt where lt mode1 gt is the tag of the model node to attach the interpolation function Then you can interpolate data specified by a table inside the function default or specified in an external file BUILDING MODELS When using an interpolation table set the interpolation data for each row of the table with the commands model func lt functag gt setIndex table lt t_value gt lt i gt 1 model func lt functag gt setIndex table lt ft_value gt lt i gt 2 where lt t_value gt is the interpolati
14. Example The property Refine constructs evaluation points by making a regular refinements of each element Each mesh edge is divided into Refine equal parts The property Smooth controls if the post data is forced to be continuous on element edges When Smooth is set to internal only elements not on interior boundaries are made continuous The property Solnum is used to select the solution to plot when a parametric eigenvalue or time dependent solver has been used to solve the problem The property Outersolnum is used to select the solution to plot when a parametric sweep has been used in the study When the property Phase is used the solution vector is multiplied with exp i phase before evaluating the expression The expressions e1 en are evaluated for one or several solutions Each solution generates an additional row in the data fields of the post data output structure The property Solnum and t control which solutions are used for the evaluations The Solnum property is available when the data set has multiple solutions for example in the case of parametric eigenfrequency or time dependent solutions The t property is available only for time dependent problems If Solnum is provided the solutions indicated by the indices provided with the Solnum property are used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated For time dependent problems the var
15. For a list of the syntax of the numerical results type available see About 7 a Results Commands in the COMSOL Java API Reference Guide To store the data you need to create a table and associate the table to the numerical node model result table create lt tabletag gt Table model result numerical lt numtag gt set table lt tabletag gt where lt tabletag gt is the tag of the table where you want to store the data evaluated with the numerical operations defined with the tag lt numtag gt Ifyou want to extract in MATLAB the data stored in a table you can use the methods getRealRow and getImagRow such as realRow model result table lt tabletag gt getRealRow lt idx gt imagRow model result table lt tabletag gt getRealRow lt idx gt where lt idx gt is the column index of the table lt tabletag gt ANALYZING THE RESULTS 109 110 For data evaluation in MATLAB you can also use the function mpheval mphevalpoint mphglobal mphint2 mphinterp mphmax mphmean and mphmin E Extracting Results in the chapter Working with Models See Also Exporting Data Use the export node to generate an animation or to export data to an external file ASCII format ANIMATION EXPORT Animations can be defined as two different types a movie or an image sequence The movie generates file formats such as GIF gif AVI avi or flash swf the image sequence generates a sequence of im
16. LiveLink for MATLAB Users Guide VERSION 4 3a Ne COMSOL LiveLink for MATLAB User s Guide 2009 2012 COMSOL Protected by U S Patents 7 519 518 7 596 474 and 7 623 991 Patents pending This Documentation and the Programs described herein are furnished under the COMSOL Software License Agreement www comsol com sla and may be used or copied only under the terms of the license agree ment COMSOL COMSOL Desktop COMSOL Multiphysics and LiveLink are registered trademarks or trade marks of COMSOL AB MATLAB is a registered trademark of The MathWorks Inc Other product or brand names are trademarks or registered trademarks of their respective holders Version October 2012 COMSOL 4 3a Contact Information Visit www comsol com contact for a searchable list of all COMSOL offices and local representatives From this web page search the contacts and find a local sales representative go to other COMSOL websites request information and pricing submit technical support queries subscribe to the monthly eNews email newsletter and much more If you need to contact Technical Support an online request form is located at www comsol com support contact Other useful links include e Technical Support www comsol com support e Software updates www comsol com support updates e Online community www comsol com community e Events conferences and training www comsol com events Tutorials www comsol com prod
17. See Also 74 CHAPTER 3 BUILDING MODELS Measuring Mesh Quality Use the stat method on the meshing sequence to get information on the mesh quality The quality measure is a scalar quantity defined for each mesh element where 0 represents the lowest quality and 1 represents the highest quality The following commands show how to visualize the mesh quality for a mesh on the unit circle model ModelUtil create Model geom1 model geom create geomi 2 geom1 feature create c1 Circle geom1 runAll mesh1 model mesh create meshi1 geom1 mesh1 feature create ftrii FreeTri meshi1 run meshdset1 model result dataset create mesh1 Mesh meshdset1 set mesh mesh1 pgi model result create pg1 2 meshploti pgi feature create meshi Mesh meshploti set data meshi meshploti set filteractive on meshploti set elemfilter quality meshplot1 set tetkeep 0 25 mphplot model pgi meshploti set elemfilter qualityrev meshplot1 run mphplot model pg1 These commands display the worst 25 and the best 25 elements in terms of mesh element quality See how in Figure 3 17 the triangular mesh elements in the plot to the right are more regular than those in the left plot this reflects the fact that a quality WORKING WITH MESHES 75 76 CHAPTER 3 measure of 1 corresponds to a uniform triangle while 0 means th
18. Use LiveLink for MATLAB to retrieve at the MATLAB workspace low level information of the COMSOL finite element model In this section e The Extended Mesh Xmesh e Extracting Xmesh Information The Extended Mesh Xmesh The extended mesh xmesh is the finite element mesh that is used to compute the solution This contains the information about elements nodes and degrees of freedom such as DOF names position of the nodes in the assembled matrix system or how elements and nodes are connected Extracting Xmesh Information The function mphxmeshinfo returns the extended mesh information To get the xmesh information of the current solver and mesh node enter the command info mphxmeshinfo model where info is a MATLAB structure that contains the fields listed in this table FIELDS DESCRIPTION soltag Tag of the solver node ndofs Number of degrees of freedom fieldnames List of field variables names fieldndofs Number of degrees of freedom for each field variables meshtypes List of the mesh type geoms Tag of the geometry node used in the model dofs Structure containing the dofs information nodes Structure containing the nodes information elements Structure containing the elements information RETRIEVING XMESH INFORMATION 159 160 The dofs substructure contains the fields listed in the following table FIELDS DESCRIPTION geomnums Index of the geometry tag for each dofs coords Coordin
19. mesh1 runCurrent meshi feature create convi Convert meshi1 run mphmesh model The result is illustrated in the Figure 3 15 Figure 3 15 Mesh using free quad elements left and converted mesh from quad to triangle right Importing External Meshes and Mesh Objects It is possible to import meshes to COMSOL Multiphysics using the following formats e COMSOL Multiphysics text files extension mphtxt e COMSOL Multiphysics binary files extension mphbin e NASTRAN files extension nas or bdf For a description of the text file format see the COMSOL Multiphysics Reference Guide IMPORTING MESHES TO THE COMMAND LINE To import a mesh stored in a supported format use the Import feature The following commands import and plot a NASTRAN mesh for a crankshaft model ModelUtil create Model model geom create geom1 3 meshi model mesh create mesh1 geom1 impi meshi feature create imp1 Import WORKING WITH MESHES 73 model modelPath dir COMSOL43a models COMSOL_Multiphysics Structural_Mechanics imp1 set filename crankshaft nas mesh1 feature imp1 importData mesh1 run mphmesh model Where dir is the path of root directory where COMSOL Multiphysics is installed The above command sequence results in Figure 3 16 Figure 3 16 Imported NASTRAN mesh For additional properties supported see Import in the COMSOL Java a API Reference Guide
20. mphversion model v mphversion returns the COMSOL Multiphysics version number that MATLAB is connected to as a string v vm mphversion model returns the COMSOL Multiphysics version number that MATLAB is connected to as a string in the variable v and the version number of the model in the variable vm mphload mphsave CHAPTER 6 COMMAND REFERENCE mphviewselection Purpose Display a geometric entity selection in a MATLAB figure Syntax mphviewselection model geomtag number entity entity mphviewselection model seltag Description mphviewselection model geomtag number entity entity displays the geometric entity number of type entity in MATLAB figure including the representation of the geometry geomtag mphviewselection model seltag displays the geometric entity selection seltag ina MATLAB figure including the representation of the geometry The function mphviewselection accepts the following property value pairs TABLE 6 25 PROPERTY VALUE PAIRS FOR THE MPHVIEWSELECTION FUNCTION PROPERTY VALUE DEFAULT DESCRIPTION Edgecolor Char RGB k Color for edges array Edgecolorselected RGB array 1 0 0 Color for selected edges Edgelabels on off off Show edge labels Edgelabelscolor Char RGB g Color for edge labels array Edgemode on off on Show edges Entity Domain Set the selected entity boundary type edge point Facealpha Double 1 Set transparency value Facecolor R
21. tablRealRow tablImagRow model result table lt tbltag gt getRealRow lt i gt model result table lt tbltag gt getImagRow lt i gt tab1RealERow and tablImagRow are available at the MATLAB workspace as Nx1 array where N is the number of rows of the table a Table in the COMSOL Java API Reference Guide See Also 0 The links to features described outside of this user guide do not work in the PDF only from within the online help Important To locate and search all the documentation for this information in COMSOL select Help gt Documentation from the main menu and either Tp enter a search term or look under a specific module in the documentation tree Extracting Data at Node Points The function mpheval lets you evaluate expressions on nodes points The function output is available as a structure in the MATLAB workspace Call the function mpheval as in this command pd mpheval model lt expr gt CHAPTER 4 WORKING WITH MODELS where lt expr gt is a string cell array that lists the COMSOL expression to evaluate The expression has to be defined in a COMSOL model object in order to be evaluated pd is a structure with the following fields e expr contains the list of names of the expressions evaluated with mpheval e dl contains the value of the expression evaluated The columns in the data value fields correspond to node point coordinates in columns in the field p In case of
22. v1 vn mphmax model e1 en edim also returns the units of the maximum in a 1xN cell array The function mphmax accepts the following property value pairs TABLE 6 13 PROPERTY VALUE PAIRS FOR THE MPHMAX COMMAND PROPERTY PROPERTY VALUE DEFAULT DESCRIPTION Dataset String active Data set tag solution data set Matrix off on on Returns data as a matrix or as a cell Outersolnum Positive integer 1 Solution number for array parametric sweep Selection Integer vector all Selection list or named string all selection Solnum Integer vector all Solution for evaluation end all Squeeze on off on Squeeze singleton dimensions T Double array Time for evaluation The property Dataset controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on Solution Data Sets The maximum expressions e1 n is evaluated for one or several solutions Each solution generates an additional column in the returned matrix The property Solnum and t control which solutions are used for the evaluation The Solnum property is available when the data set has multiple solutions for example in the case of parametric eigenfrequency or time dependent solutions The t property is COMMAND REFERENCE mphmax Example See also available only for time dependent problems If Solnum is provided the solutions indicated by the in
23. Click Copy to copy syntax to the clipboard and then paste it in your script The Model Tree list is slightly different to the Model Builder list available in the COMSOL Desktop This is because mphnavigator displays all Ei feature nodes and does not use the same filter as in the COMSOL Desktop to order the available feature nodes Note THE PROPERTIES SECTION Properties Property Value 1 adjface selection a 2 angle 0 3 createselection off 4 ledge selection 5 face selection 6 genpoints 0 0 0 1 0 0 0 1 0 7 offset 0 ee origin facecenter eo planetype quick 10 quickplane xz 11 quickx 0 12 quicky 0 Copy Table Copy The Properties section lists the properties of a selected feature node and the associated values Click Copy Table to copy the entire properties table to the clipboard then paste into a text or spreadsheet editor Click Copy to copy a selected cell in the properties table NAVIGATING THE MODEL 165 166 THE METHODS SECTION m Methods ter Name Value a crcuornt 2 author COMSOL E 3 autoRebuild on J 4 check 1 5 comments 6 _ current fin 7 _ dateCreated Sep 23 2011 3 36 53 PM 8 dateModified Sep 23 2011 3 36 53 PM 9 exists 1 4 java lang String angularUnit deg Copy The Methods section lists all the methods associated to the feature node selected in the Mode
24. Parametric sweep parameter values Number of solution vectors stored Number of reaction forces vectors stored 252 CHAPTER 6 COMMAND REFERENCE mphsolinfo TABLE 6 23 FIELDS IN THE INFO STRUCT FIELD CONTENT NUadj Number of adjacency vectors stored NUfsens Number of functional sensitivity vectors stored NUsens Number of forward sensitivity vectors stored You can use the function mphgetu to obtain the actual values of the solution vector Note that these functions are low level functions and you most often would use functions such as mphinterp and mpheval to extract numerical data from a model Examplee Load stress_in_pulley mph from the Model Library model mphload stress_in_pulley mph Get the information of the active solution object info mphsolinfo model Get the information of the second solution object info mphsolinfo model solname sol2 See also mphgetu mphxmeshinfo 253 mphstart 254 Purpose Syntax Description Connect MATLAB to a COMSOL server mphstart mphstart port mphstart ipaddress port mphstart ipaddress port comsolpath mphstart creates a connection with a COMSOL server using the default port number which is 2036 mphstart port creates a connection with a COMSOL server using the specified port number port mphstart ipaddress port creates a connection with a COMSOL server using the specified IP address ipaddress and the port number port
25. Refer to MATLAB help to get more information about the MATLAB commands for while if switch try catch break and continue EXAMPLE GEOMETRY PARAMETRIZATION In this example you will see how to proceed to geometry parametrization using a MATLAB for loop The model consists of the busbar example available in the COMSOL Multiphysics model see the Introduction to COMSOL Multiphysics In this example the loop iterate over the busbar width wbb The solution for each parameter value is displayed using the second plot group defined in the COMSOL model All the results are plotted in the same figure model mphload busbar w 5e 2 10e 2 15e 2 20e 2 for i 1 4 model param set wbb w i model study std1 run subplot 2 2 1 mphplot model pg2 rangenum 1 end CHAPTER 4 WORKING WITH MODELS The resulting figure is shown below Surface Current density norm Arms ao Surface Current density norm Aimy Fo 0 z340 01 0 05 0 0 1 4 0 08 0 a Surface Current density norm A Surface Current density norm 0 1 8 0 05 6 0 08 4 2 5 0 15 0 Jl A 40 10 RUNNING MODELS IN A LOOP 139 140 Running Models in Batch Mode Use LiveLink for MATLAB to models in batch mode At the MATLAB prompt you can execute commands to set up the batch job using the COMSOL built in method or run custom scripts directly from a command line In this section The Batch Node e Ru
26. Square geom1 run mati model material create mat1 def mati materialModel def def set thermalconductivity 4e2 ht model physics create ht HeatTransfer geom1 hs1 ht feature create hs1 HeatSource 2 hs1 selection set 1 hs1 set Q 1 1e5 tempi ht feature create temp1 TemperatureBoundary 1 temp1 selection set 1 2 meshi model mesh create mesh1 geom1 disi meshi feature create dis1 Distribution dis1 selection set 1 2 dist set numelem 2 mesh1 feature create map1 Map std1 model study create std1 std1 feature create stat Stationary std1 run CHAPTER 4 WORKING WITH MODELS To extract the solution vector of the computed solution run the function mphgetu as in this command U mphgetu model To assemble and extract the eliminated stiffness matrix and the eliminated load vector set the linearization point to the initial value expression by entering MA mphmatrix model soli Out Ke Lce Null ud uscale initmethod sol initsol zero Solve for the eliminated solution vector using the extracted eliminated system Uc MA Nul1 MA Kc MA Lc Combine the eliminated solution vector and the particular vector UO Uc MA ud Scale back the solution vector U1 1 U0 MA uscale Now compare both solution vector U and U1 computed by COMSOL and by the matrix operation respective
27. input set wp1 geom1 run wp1 mesh1 model mesh create meshi geom1 sizei mesh1 feature create size1 Size size1 selection geom geom1 1 size1 selection set 18 sizei set hmax 0 06 ftril meshi feature create ftriit FreeTri ftril selection geom geomi 2 ftril selection set 10 cpf1 mesh1 feature create cpf1 CopyFace cpf1 selection source geom geom1 2 cpf1 selection destination geom geom1 2 cpf1 selection source set 10 cpf1 selection destination set 1 swi meshi feature create swi Sweep sw1 selection sourceface geom geomi 2 sw1 selection targetface geom geomi 2 BUILDING MODELS meshi1 run mphmesh model The algorithm automatically determines how to orient the source mesh on the target boundary The result is shown in Figure 3 13 Figure 3 13 Prism element obtained with the CopyFace and Sweep features To explicitly control the orientation of the copied mesh use the EdgeMap attribute The command sequence emi cpfi feature create em1 EdgeMap em1 selection srcedge set 18 em1 selection dstedge set 2 mesh1 feature remove sw1 meshi feature create fteti FreeTet mesh1 run mphmesh model copies the mesh between the same boundaries as in the previous example but now the orientation of the source mesh on the target boundary is different The domain is then meshed
28. iteration For automatic geometry or mesh generation you can use it to set the model properties with alternative values that circumvent the problem Displaying Warnings and Errors in the Model Use the command mphshowerrors to search in a given model object for warning or error nodes To display the error and warning messages and their location in the model object type the command HANDLING ERRORS AND WARNINGS 169 mphshowerrors model Alternatively mphshowerrors can also return the error and warning information in a MATLAB variable str mphshowerrors model where str is an Nx2 cell array with N the number of error and warning nodes that contain the model object str i 1 which contains the location in the model of the i th error warning message and str i 2 contains the message of the ith error warning message 170 CHAPTER 4 WORKING WITH MODELS Improving Performance for Large Models Memory management is a key to successful modeling In COMSOL Multiphysics the finite element model can store a large amount of data depending on the complexity of the model Exchanging such a large amount of data between MATLAB and the COMSOL server can be problematic in terms of memory or computational time This section discusses the model settings if you are experiencing memory problems or slowness of command execution e Setting Java Heap Size e Disabling Model Feature Update e Disabling The Model History Setting Java
29. lt outersolnum gt where lt outersolnum gt is a positive integer array corresponding to the outer solution index The default setting uses the first outer solution for the data evaluation e To evaluate the expression data at a specific time use the property t data mphmean model lt expr gt edim t lt time gt where lt time gt is a double array The default value corresponds to all the stored time steps OUTPUT FORMAT The function mphmean also supports other output formats To extract the unit of the evaluated expression define an extra output variable data unit mphmean model lt expr gt edim with unit is a 1xN cell array where N is the number of expressions to evaluate By default mphmean returns the results as a squeezed singleton To get the full singleton set the squeeze property to off data mphmean model lt expr gt edim squeeze off Set the property matrix to off to return the data as a cell array instead of a double array data mphmean model lt expr gt edim matrix off SPECIFY THE INTEGRATION SETTINGS You can specify integration settings such as an integration method or integration order to perform the mean operation The available integration properties are e method specify the integration method which can be either integration or summation CHAPTER 4 WORKING WITH MODELS data mphmean model lt expr gt edim method method where method can be i
30. p1 Point p1 set p 0 5 geom1 run to add a point object located at x 0 5 to the geometry To plot the result enter mphgeom model geom1 vertexmode on 066p 0 4F 0 2 0 2 O6F CREATING A 2D GEOMETRY USING PRIMITIVE GEOMETRY OBJECTS Q For more information about 2D geometry modeling see Creating a 2D See Also Geometry Model in the COMSOL Multiphysics User s Guide Creating Composite Objects Use a model object with a 2D geometry Enter model ModelUtil create Model WORKING WITH GEOMETRY 35 36 CHAPTER 3 geom2 model geom create geom2 2 Continue by creating a rectangle with side length of 2 and centered at the origin sqi geom2 feature create sqi Square sqi set size 2 sqi set base center The property size describes the side lengths of the rectangle and the property pos describes the positioning The default is to position the rectangle about its lower left corner Use the property base to control the positioning Create a circular hole with a radius of 0 5 centered at 0 0 ci geom2 feature create c1 Circle c1 set r 0 5 c1 set pos 0O 0 The property r describes the radius of the circle and the property pos describes the positioning The property pos could have been excluded because the default position is the origin The default is to position the circle about its center Drill a hole in the rectangle by subtracti
31. server path Any files saved in the MPH format can be loaded by the COMSOL Desktop In addition the model can be saved as a Model M file model save model_name m The models are not automatically saved between MATLAB sessions Note Exchanging Models Between MATLAB and the COMSOL Desktop It is possible to alternate between the MATLAB scripting interface and the COMSOL graphical user interface in order to edit or modify the model object When running THE MODEL OBJECT 29 30 COMSOL with MATLAB the model object is stored on the COMSOL server You can directly load the model object in the COMSOL Desktop from the COMSOL server or conversely export the model object available in the COMSOL Desktop to the COMSOL server EXPORTING FROM THE COMSOL DESKTOP A MODEL TO MATLAB In the COMSOL Desktop use the option Export to Server from the File menu to send the model object to the COMSOL server that is connected with MATLAB Once the model object is on the COMSOL server create a link in the MATLAB prompt 1 Open a model in the COMSOL Desktop 2 From the File menu choose Client Server gt Export Model to Server f Export Model to Server ax Server User Model Server localhost Username user Model Model Port 2036 Password eeeceeececeecoes V Remember password Cancel 3 Make sure that the Server the default is Localhost and the Port the default is 2036 fields are set with the correc
32. 0 5 Plot the titanium blot domains in green color mphviewselection model seli facecolorselected 0 1 0 See also mphgeom mphselectbox mphselectcoords 260 CHAPTER 6 COMMAND REFERENCE mphxmeshinfo Purpose Syntax Description Example Extract information about the extended mesh info mphxmeshinfo model The Xmesh information provide information about the numbering of elements nodes and degrees of freedom DOFs in the extended mesh and in the matrices returned by mphmatrix and mphgetu Information is only available on StudyStep and Variables features The function mphxmeshinfo accepts the following property value pairs TABLE 6 26 PROPERTY VALUE PAIRS FOR THE MPHVIEWSELECTION FUNCTION PROPERTY VALUE DEFAULT DESCRIPTION Solname String Active Solution object tag solution object Studysteptag String Study step node tag Meshcase Positive First mesh Mesh case tag integer String The function xmeshinfo returns a structure with the fields shown in the table below TABLE 6 27 FIELD IN THE RETURNED STRUCTURE FROM MPHXMESHINFO FIELD DESCRIPTION Solname Tag of the solution object Ndofs Number of DOFs Fieldnames Names of the field variables Fieldndofs Number of DOFs per field name Meshtypes Types of mesh element Dofs Structure with information about the degrees of freedom Nodes Struct with information about the nodes Elements Struct with information about each element typ
33. 127 Evaluating a Global Expression 2 2 1 2 1 ew ee 129 Evaluating a Global Matrix 2 2 2 ee ee ee D8 Evaluating a Maximum of Expression 2 2 2 2 O31 Evaluating an Expression Average 2 1 wwe ee 133 Evaluating a Minimum of Expression 2 2 1 135 Running Models in a Loop 137 The Parametric Sweep Node Fe an cet hee BF Running Model in a Loop Using the MATLAB Tools 137 Running Models in Batch Mode 140 The Batch Node riia Ue ot Goda chy ap Ae Gets 2140 Running A COMSOL M file In Batch Mode 2 ee 140 Running A COMSOL M file In Batch Mode Without Diipa E E Working with Matrices 142 Extracting System Matrices 2 2 2 2 ww ee ee ee ee 142 Set System Matrices inthe Model a 2 2 2 2 we 145 Extracting State Space Matrices 2 2 2 ww ww ISO Extracting Solution Information and Solution Vector 155 Obtaining Solution Information 2 2 2 ee 55 Extracting Solution Vector 2 2 2 a ee ee ee 157 Retrieving Xmesh Information 159 The Extended Mesh Xmesh 2 2 2 2 ee ee ee 159 Extracting Xmesh Information 2 159 6 CHAPTER Navigating the Model Navigating the Model Object Using a GUI Navigating The Model Object At The Command Line Finding Model Expressions Getting Feature Model Properties Getting Model Expressions Getting Selection Information Handling Errors and Warnings
34. COMSOL 3 5A COMPATIBILITY 175 176 CHAPTER 4 WORKING WITH MODELS Calling MATLAB Functions This section introduces you to the MATLAB function callback from the COMSOL Desktop and COMSOL model object In this chapter e The MATLAB Function Feature Node 177 178 The MATLAB Function Feature Node MATLAB functions are global in scope and you can use them in a model to define model settings such as parameters material properties and boundary conditions When running the model COMSOL automatically starts a MATLAB process that evaluates the function and returns the value to the COMSOL model To call a MATLAB function from within the model you do not need to start COMSOL with MATLAB starting the COMSOL Desktop is Ei sufficient The MATLAB process starts automatically to evaluate the Note B function CHAPTER 5 e Defining a MATLAB Function in the COMSOL Model e Adding a MATLAB Function with the COMSOL API Java Syntax Defining a MATLAB Function in the COMSOL Model ADDING THE MATLAB FUNCTION NODE To evaluate a MATLAB function from within the COMSOL model you need to add a MATLAB node in the model object where the function name the list of the arguments and if required the function derivatives are defined CALLING MATLAB FUNCTIONS To add a MATLAB function node right click the Global Definitions node and select Functions gt MATLAB Pi Parameters a Variables Functions H Load Group
35. DESKTOP 23 24 CHAPTER 2 GETTING STARTED This chapter gives an overview of the model object and provides an introduction Building Models to building models using the LiveLink interface In this chapter The Model Object Working with Geometry Working with Meshes Modeling Physics Creating Selections Computing the Solution Analyzing the Results 25 26 The Model Object While working with the LiveLink interface in MATLAB you work with models through the model object Use methods to create modify and access your model In this section e Important Notes About the Model Object e The Model Object Methods e The General Utility Functionality e Loading and Saving a Model e Exchanging Models Between MATLAB and the COMSOL Desktop Important Notes About the Model Object The following information should be considered regarding the model object e All algorithms and data structures for the model are integrated in the model object e The model object is used by the COMSOL Desktop to represent your model This means that the model object and the COMSOL Desktop behavior are virtually identical e The model object includes methods for setting up and running sequences of operations to create geometry meshes and for solving your model LiveLink for MATLAB includes the COMSOL Java API which is a Java based programming interface to COMSOL In addition the product includes a number of M file utility function
36. Errors and Warnings A Using MATLAB Tools To Handle COMSOL EA Displaying Warnings and Errors in the Model Improving Performance for Large Models Setting Java Heap Size Disabling Model Feature Update Disabling The Model History Creating a Custom GUI COMSOL 3 5a Compatibility Chapter 5 Calling MATLAB Functions The MATLAB Function Feature Node Defining a MATLAB Function in the COMSOL Model Setting the Function Directory Path in MATLAB Adding a MATLAB Function with the COMSOL API Java ae Function Input Output Considerations Updating Functions Defining Function Derivatives Using the MATLAB Debugger Windows Only Chapter 6 Command Reference Summary of Commands Commands Grouped by Function 162 162 166 167 168 168 168 169 169 169 169 171 171 172 172 174 175 178 178 182 183 183 184 184 185 188 190 Introduction This guide introduces you to LiveLink for MATLAB which extends your COMSOL modeling environment with an interface between COMSOL Multiphysics and MATLAB The COMSOL Java API Reference Guide provides additional documentation of the API In this chapter e About LiveLink for MATLAB e Help and Documentation 8 CHAPTER I About LiveLink for MATLAB LiveLink for MATLAB connects COMSOL Multiphysics to the MATLAB scripting environment Using this functionality you can do the following SET UP MODELS FROM A SCRIPT LiveLink for MATLAB i
37. Heap Size COMSOL stores the data in Java If you are experiencing memory problems during meshing postprocessing operations or when exchanging data between the COMSOL server and MATLAB this may mean that the Java Heap size is set with too low a value EI Increasing the memory allocated for the Java process necessarily decreases the memory available for the solver Note THE COMSOL SERVER JAVA HEAP SIZE You can access the Java Heap size settings for the COMSOL server process in the comsolserver ini file that can be found in the COMSOL43a bin lt arch gt directory lt arch gt correspond to the architecture of the machine where the COMSOL server is running Edit the file with a text editor the Java heap settings are set as Xss4m Xms40m Xmx1024m XX MaxPermSize 256m The values are given in Mb modify these value to satisfy the model requirements IMPROVING PERFORMANCE FOR LARGE MODELS 171 172 THE MATLAB JAVA HEAP SIZE To modify the Java heap size you need to edit the java opts file available under the COMSOL with MATLAB start up directory The java opts file is stored by default with the following settings Xss4m Xmx768m XX MaxPermSize 256m The values are given in Mb modify these value to satisfy the model requirements To modify the MATLAB Java Heap size the java opts file has to be stored at the MATLAB start up directory This is the case when starting COMSOL with MATLAB In case you are
38. MPHINT2 COMMAND PROPERTY PROPERTY VALUE DEFAULT DESCRIPTION Dataset String active Data set tag solution data set Intorder Positive integer 4 Integration order Intsurface on off off Compute surface integral Intvolume on off off Compute volume integral Matrix off on on Returns data as a matrix or as a cell Method auto auto Integration method integration summation Outersolnum Positive integer 1 Solution number for parametric sweep Selection Integer vector all Selection list or named string all selection Solnum Integer vector all Solution for evaluation end all Squeeze on off on Squeeze singleton dimensions T Double array Time for evaluation The property Dataset controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on Solution Data Sets 219 mphint2 220 Example The expressions e1 en are integrated for one or several solutions Each solution generates an additional column in the returned matrix The property Solnum and t control which solutions are used for the integrations The Solnum property is available when the data set has multiple solutions for example in the case of parametric eigenfrequency or time dependent solutions The t property is available only for time dependent problems If Solnum is provided the solutions indicated by the indices provided with the Solnum property a
39. Note For example using the Hankel function described in Example Define the Hankel Function define the function derivative by entering the following settings in the table FUNCTION ARGUMENT FUNCTION DERIVATIVE besselh nu besselh nu 1 x besselh nut 1 x 2 besselh x besselh 0 x besselh 2 x 2 v Derivatives Function Argument Partial derivative besselh nu besselh nu 1 x besselh nu 1 x 2 besselh x besselh 0 x besselh 2 x 2 t g Function besselh Argument x Partial derivative besselh 0 x besselh 2 x 2 Using the MATLAB Debugger Windows Only Ifyou are running on Windows you can benefit of the MATLAB debugger when running MATLAB functions in the COMSOL model To activate the MATLAB debugger you first need to start the MATLAB Desktop from the MATLAB process that is started when evaluating the function in COMSOL At the MATLAB prompt enter the command desktop THE MATLAB FUNCTION FEATURE NODE 185 In the MATLAB Desktop edit the function M file and add a break point at the desired line When the COMSOL model is run the MATLAB debugger automatically stops at the break point You can then verify the intermediate value of the function variables 186 CHAPTER 5 CALLING MATLAB FUNCTIONS Command Reference The main reference for the syntax of the commands available with LiveLink for MATLAB is the COMSOL Java API Reference Guide This section documents additional interface functions t
40. a MATLAB figure The function mphmesh accepts the following property value pairs TABLE 6 15 PROPERTY VALUE PAIRS FOR THE MPHMESH COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Parent Double Parent axis Edgecolor Char k Edge color Edgelabels on off off Show edge labels Edgelabelscolor Char k Color for edge labels Edgemode on off on Show edges Facealpha Double 1 Set transparency value Facelabels on off off Show face labels Facelabelscolor Char k Color for face labels Facemode on off on Show faces Meshcolor Char flat Color for face element Vertexlabels on off off Show vertex labels Vertexlabelscolor Char k Color for vertex labels Vertexmode on off off Show vertices Load the example model shell_diffusion mph from the Model Library model mphload shell_diffusion mph Plot the model mesh mphmesh model Plot the mesh with a colored element and transparency set to 0 5 mphmesh model meshi edgecolor b facealpha 0 5 meshcolor r mphgeom mphmeshstats mphplot CHAPTER 6 COMMAND REFERENCE mphmeshstats Purpose Syntax Description Return mesh statistics and mesh data information stats mphmeshstats model stats mphmeshstats model meshtag stats data mphmeshstats model meshtag stats mphmeshstats model returns mesh statistics of the model mesh case in the structure str stats mphmeshstats model meshtag returns mesh statistics of a mesh case meshtag i
41. a model object including the geometry represented by the contour value 40 At the MATLAB prompt enter these commands p peaks 7 5 c h contourf p WORKING WITH GEOMETRY 49 Clabel c h model mphimage2geom p 40 figure 2 mphgeom mode1l Use the property type to create closed or open curves For example to create a geometry following contour 40 with closed curves enter model mphimage2geom p 40 type closed mphgeom model1 45 40 25 20 15 10 15 20 25 30 35 To scale the geometry use the scale property Using the current model scale the geometry with a factor of 0 001 le 3 40 45 50 model mphimage2geom p 40 scale 1e 3 50 CHAPTER 3 BUILDING MODELS mphgeom model 0 046 0 04 0 036 0 03 0 026 0 02 0 015 0 01 0016 002 0025 003 0035 004 0045 005 To insert a rectangle in the geometry that has an outer domain surrounding the created contour set the property rectangle to on model mphimage2geom p 40 rectangle on mphgeom model 50 45 40 35 30 25 20 WORKING WITH GEOMETRY 5l 52 Working with Meshes This section describes how to set up and run meshing sequences in a model e The Meshing Sequence Syntax e Displaying the Mesh e Mesh Creation Functions e Importing External Meshes and Mesh Objects e Measuring Mesh Quality e Getting Mesh Statistics Information e Getting and Setting Mesh Data e Creating Mes
42. accessed from MATLAB The Command Reference chapter describes the function available for use with LiveLink for MATLAB The COMSOL Java API Reference Guide contains reference documentation that describes the methods in the model object M FILES Save models as an M file Use the COMSOL Desktop to get your first model implemented using the COMSOL Java API Set up the model using the graphical user interface then save the model as an M file Next go to the File menu and select Save as M file This generates an M function that can be run using COMSOL with MATLAB THE MODEL LIBRARY Study the LiveLink for MATLAB Model Library LiveLink for MATLAB includes a model library with detailed example models Use the function mphmodellibrary at INTRODUCTION the command line to get a list of available models The following are some models that can help get you started e Learn how to activate and deactivate domains alternatively during a transient analysis See the model Domain Activation and Deactivation model name domain_activation_llmatlab e Homogenization in a Chemical Reactor model name homogenization_llmatlab shows how to simulate a periodic homogenization process in a space dependent chemical reactor model This homogenization removes concentration gradients in the reactor at a set time interval e Convective Heat Transfer with Pseudo Periodicity model name pseudoperiodicity_11matlab simulates convective heat transfer in
43. and COMSOL Multiphysics Reference Guide describe all interfaces and functionality included with the basic COMSOL Multiphysics license These guides also have instructions about how to use COMSOL Multiphysics and how to access the documentation electronically through the COMSOL Multiphysics help desk To locate and search all the documentation in COMSOL Multiphysics e Press Fl or select Help gt Help E from the main menu for context help e Press Ctrl F1 or select Help gt Documentation 7 from the main menu for opening the main documentation window with access to all COMSOL documentation e Click the corresponding buttons qa or F on the main toolbar and then either enter a search term or look under a specific module in the documentation tree If you have added a node to a model you are working on click the Help button E in the node s settings window or press F1 to learn more about it Under More results in the Help window you find a link with a search string for the node s name Click this link to find all occurrences of g the node s name in the documentation including model documentation and the external COMSOL website This can help you find more information about the use of the node s functionality as well as model Tip examples where the node has been used THE MODEL LIBRARY Fach model comes with documentation that includes a theoretical background and step by step instructions to create
44. assignment methods can be appended to each other something setIndex property lt value gt lt index gt The name argument is a string with the name of the property lt value gt is the value to set the property which can be a MATLAB variable value and lt index gt is the index in the property table When using a MATLAB variable make sure that the value corresponds to the model unit system COMSOL can automatically take care of the unit conversation in this case converting the MATLAB integer double variable to a string variable and using the set method as something setIndex property num2str lt value gt unit lt index gt where unit is the unit you want to set the value property Using a MATLAB Function to Define Model Properties Use MATLAB Function to define the model property The function can either be declared within the model object or called at the MATLAB prompt CALLING MATLAB FUNCTIONS WITHIN THE COMSOL MODEL OBJECT LiveLink for MATLAB enables you to declare a MATLAB M function directly from within the COMSOL model object This is typically the case if you want to call MATLAB M function from the COMSOL Desktop The function being declared within the model object accepts any parameter variable or expression arguments defined in the COMSOL model object However to use a variable defined at the MATLAB prompt the variable has to be transferred first in the COMSOL model as a parameter for instance see ho
45. by the free mesh resulting in the mesh in Figure 3 14 In this case it is not possible to create a swept mesh on the domain because the boundary meshes do not match in the sweeping direction WORKING WITH MESHES 71 72 Figure 3 14 Free tetrahedral mesh after the use of the CopyFace feature CONVERTING MESH ELEMENTS Use the Convert feature to convert meshes containing quadrilateral hexahedral or prism elements into triangular meshes and tetrahedral meshes In 2D the function splits each quadrilateral element into either two or four triangles In 3D it converts each prism into three tetrahedral elements and each hexahedral element into five six or 28 tetrahedral elements To control the method used to convert the elements use the property splitmethod The default value is diagonal which results in two triangular elements in 2D and five or six tetrahedral elements in 3D Q For additional properties supported see Convert in the COMSOL Java See Also API Reference Guide CHAPTER 3 This example demonstrates how to convert a quad mesh into a triangle mesh model ModelUtil create Model geom1 model geom create geom1 2 geom1 feature create c1 Circle geom1 feature create r1 Rectangle inti geom1 feature create int1 Intersection BUILDING MODELS int1 selection input set c1 r1 meshi model mesh create meshi geom1 mesh1 feature create fqi FreeQuad
46. can also be end to evaluate the expression for the last inner solution By default the evaluation is performed using the last inner solution outersolnun specify the outer solution number for data evaluation Outer solutions are generated with parametric sweeps data mphinterp model lt expr gt coord lt coord gt outersolnum lt outersolnum gt where lt outersolnum gt is a positive integer corresponding to the outer solution index The default settings use the first outer solution for the data evaluation To evaluate the expression data at a specific time use the property t data mphinterp model lt expr gt coord lt coord gt t lt time gt where lt time gt is a double array The default value corresponds to all the stored time steps EXTRACTING RESULTS 123 124 e phase specify the phase in degrees data mphinterp model lt expr gt coord lt coord gt phase lt phase gt where lt phase gt is a double value OUTPUT FORMAT The function mphinterp returns in the MATLAB workspace a double array It also supports other output format To evaluate several expressions at once make sure that the same number of output variables are defined as there are expressions specified d1 dn mphinterp model el en coord lt coord gt To extract the unit of the evaluated expression define an extra output variable data unit mphinterp model lt expr gt co
47. define the study node The minimal definition for the study node consists in a study step that define the type of study to use to compute the solution To add a study step to the study node use the syntax model study lt studytag gt feature create lt ftag gt operation where lt studytag gt is the string identifying the study node The string lt ftag gt is a string that is defined to refer to the study step The string operat ion is one of the basic study types such as Stationary Transient or Eigenfrequency and more a Study Types in the COMSOL Reference Guide See Also To specify a property value pair for a study step enter model study lt studytag gt feature lt ftag gt set property lt value gt where lt ftag gt is the string identifying the study step To generates the default solver sequence associated with the physics solved in the model and compute the solution run the study node with the command model study lt studytag gt run BUILDING MODELS model study in the COMSOL Java API Reference Guide See Also The Solver Sequence Syntax If you don t want to use the default solver sequence created by the study node you have the possibility to manually create one To create a solver sequence enter model sol create lt soltag gt where lt soltag gt is a string used to refer to the solver sequence associated to a solution object A solver sequence has to be connecte
48. e 1 for edges boundaries and e 0 for points Set the domain entity indices in the selection node with the command model selection lt seltag gt set lt idx gt where lt idx gt is an array of integers that list the geometric entity indices to add in the selection Coordinate Based Selections DEFINING A BALL SELECTION NODE The Ball selection node is defined by a center point and a radius The selection can include geometric entities that are completely or partially inside the ball The selection can be set up by using either the COMSOL API directly or the mphselectcoords function Ball Selection Using the COMSOL API To add a ball selection to a model object enter model selection create lt seltag gt Ball To set the coordinates lt x0 gt lt y0 gt lt z0 gt of the selection center point enter model selection lt seltag gt set posx lt x0 gt model selection lt seltag gt set posy lt y0 gt model selection lt seltag gt set posz lt z0 gt where lt x0 gt lt y0 gt lt z0 gt are double values Specify the ball radius lt ro gt with the command model selection lt seltag gt set r lt r0 gt where lt r0 gt is a double floating point value To specify the geometric entity level enter CREATING SELECTIONS 91 model selection lt seltag gt set entitydim edim where edim is an integer defining the space dimension value 3 for domains 2 for boundaries doma
49. elemratio the number and distribution of mesh element layers is controlled in the extruded direction Distribution in the COMSOL Java API Reference Guide See Also Figure 3 9 Extruded 3D prism mesh COMBINING UNSTRUCTURED AND STRUCTURED MESHES By specifying selections for the meshing operations swept meshing can also be combined with free meshing In this case start by free meshing domain 2 then sweep the resulting surface mesh through domain 1 as in this example WORKING WITH MESHES 65 66 CHAPTER 3 model ModelUtil create Model geom1 model geom create geom1 3 cone1 geom1 feature create cone1 Cone cone1 set r 0 3 cone1 set h 1 cone1 set ang 9 cone1 set pos 0 0 5 0 5 cone1 set axis 1 0 0 geom1 feature create blk1 Block meshi model mesh create mesh1 geom1 ftet1 mesh1 feature create ftet1 FreeTet ftet1 selection geom geom1 3 ftet1 selection set 2 swel mesh1 feature create swei Sweep swe1 selection sourceface geom geom1 2 swe1 selection targetface geom geom1 2 mesh1 run mphmesh model Figure 3 10 Combined structured unstructured mesh The left hand side plot in Figure 3 10 is obtained with this command mphgeom model geom1 facemode off facelabels on CREATING BOUNDARY LAYER MESHES For 2D and 3D geometries it is also possible to create boundary layer m
50. filter the list Enter any string in the edit field and select where to search this string in the name the expression or the description of the table entry You can also select the type you want to list The expression type can be Equation Field Tag VarNames or Weak Click Go to display the result of the search Click Clear to clear the search settings Click Copy to copy any entry of the table to the clipboard Click Close to close the mphsearch window NAVIGATING THE MODEL 167 168 Getting Feature Model Properties Use the command mphgetproperties to extract at the MATLAB prompt the properties of a specified node of the model object Use the command prop mphgetproperties model feature where expr is a MATLAB structure that lists all the properties and the value of the feature node model feature Getting Model Expressions Use the command mphgetexpressions to get at the MATLAB prompt the expressions and the descriptions of a specified node of the model object Use the command expr mphgetexpressions model feature where model feature is the node to get the expressions from and expr is an Nx3 cell array where N is the number of expressions for this node Getting Selection Information Use the function mphgetselection to retrieve the model selection information str mphgetselection model selection lt seltag gt where seltag is the tag a selection node defined in the model object The
51. format that is saved See also mphload 245 mphsearch Purpose GUI for searching expressions in the COMSOL model object Syntax mphsearch model Description mphsearch model opens a graphical user interface that can be used to search expressions in the model object model Search using a text available in the name expression or description of the variable r a E mphsearch Search COMSOL Multiphysics Sex m Search V Name E Expression Description Type Name Expression l Description Type Path 1 F_const 96485 3399 C mol Faraday constant Varnames model variable iexpr1 a 2__ G_const 6 67428E 11 m 3 kg s 2 Gravitational constant Varnames model variable iexpr1 3__ Heat_prict Tag model elem Heat_prict 4 i Field model physics jh 5 it fem Varnames model param 6 _ N_A_const 6 02214179E23 1 mo Avogadro constant Varnames model variable iexpr1 7_ R const 8 314472 J K mol Universal gas constant Varnames model variable iexprt 8 it Field model physics jh 9 v Field model physics jh 10 _ V_m_const 0 022413996 m 3 mol Molar volume of idealgas Varnames model variable iexpr1 114 _ Vtot 20 mV Varnames model param 12_ Z0_const root mu0_const root c_const Characteristic impedance of Varnames model variable iexpr1 13 aDef Advanced Tag model sol solt feature s1 feature a 14
52. function mphmin also supports other output formats To extract the unit of the evaluated expression define an extra output variable data unit mphmin model lt expr gt edim with unit is a 1xN cell array where N is the number of expressions to evaluate By default mphmin returns the results as a squeezed singleton To get the full singleton set the squeeze property to off data mphmin model lt expr gt edim squeeze off Set the property matrix to off to return the data as a cell array instead of a double array data mphmin model lt expr gt edim matrix off CHAPTER 4 WORKING WITH MODELS Running Models in a Loop Acommon use of LiveLink for MATLAB is to run models in a loop As MATLAB offers several functionalities to run loops including conditional statements and error handling you will see how all these functionality can be used together with the COMSOL Java API syntax to run COMSOL model in loop In this section e The Parametric Sweep Node e Running Model in a Loop Using the MATLAB Tools The Parametric Sweep Node Using the COMSOL Java API you can run model in loop See the section Adding a Parametric Sweep in the section Building Models Note that using the COMSOL built in function to run models in loop you can ensure the model to be saved automatically at each iteration COMSOL also offers tool to take advantage of clusters architecture Running Model in a Loop Using the MATLAB
53. geometry To plot the structure lt data gt run the command mphplot lt data gt If the data structure contains the value of several expressions set the one to display in the plot with the index property mphplot lt data gt index lt idx gt where lt idx gt is a positive integer that corresponds to the expression to plot You may select from several available color tables when visualizing data by using the colortable option mphplot lt data gt colortable colorname Obtain a list of alternatives for colorname from the on line help by typing help colortable EI mphplot supports only plotting of data structures that are of the type point line or surface evaluations from mpheval Note CHAPTER 3 BUILDING MODELS EXAMPLE PLOT MPHEVAL DATA This example extracts COMSOL data at the MATLAB prompt modifies it and plots the data in a MATLAB figure First load the Busbar model from the COMSOL Model Library Enter model mphload busbar To extract the temperature and the electric potential field use the command mpheval dat mpheval model T V selection 1 To display the temperature field using the thermal color table mphplot dat index 1 colortable thermal T 0 05 oO Now do a simple scaling of the electric potential then plot it using the default color table dat d2 dat d2 1e 3 mphplot dat index 2 ANALYZING THE RESULTS 107 108
54. gt 0 1 where lt function_name gt is a string set with the function name and lt arglist gt isa string that defines the list of the input arguments Function Input Output Considerations The functions called from COMSOL must support vector arguments of any length COMSOL calls a MATLAB function using vector arguments to reduce the number of expensive calls from COMSOL to MATLAB All common MATLAB functions such as sin abs and other mathematical functions support vector arguments When you write your own functions remember that the input arguments are vectors The output must have the same size as the input All arguments and results must be double precision vectors real or complex valued Consider the following example function where the coefficient c depends on the x coordinate function c funci x if x gt 0 6 c x 1 6 else c x 2 0 3 end THE MATLAB FUNCTION FEATURE NODE 183 184 CHAPTER 5 This function looks good at first but it does not work in COMSOL Multiphysics because the input x is a matrix e Element by element multiplication division and power must be used that is the operators and Replace expressions such as x 1 6 and x 2 0 3 with x 1 6 and x 2 0 3 respectively e The comparison x gt 0 6 returns a matrix with ones true for the entries where the expression holds true and zeros false where it is false The function evaluates the conditional st
55. indicates that other useful information is located in the named section If you are working on line click the hyperlink to go to the information directly When the link is outside of the current PDF document the text indicates this for example See The Laminar Flow Interface in the COMSOL Multiphysics User s Guide Note that if you are in COMSOL Multiphysics online help the link works The Model icon is used in the documentation as well as in COMSOL Multiphysics from the View gt Model Library menu If you are working online click the link to go to the PDF version of the step by step instructions In some cases a model is only available if you have a license for a specific module These examples occur in the COMSOL Multiphysics User s Guide The Model Library path describes how to find the actual model in COMSOL Multiphysics for example If you have the RF Module see Radar Cross Section Model Library path RF_Module Tutorial_Models radar_cross_section Another set of icons are also used in the Model Builder the model space dimension is indicated byOD ID ID axial symmetry 4 2D f 2D axial symmetry i and 3D i icons These icons are also used in the documentation to clearly list the differences to an interface feature node or theory section which are based on space dimension INTRODUCTION Getting Started In this chapter e The Client Server Architecture e Running COMSOL with MATLAB e Calling a MAT
56. instead of a double array data mphint2 model lt expr gt edim matrix off SPECIFY THE INTEGRATION SETTINGS To specify integration settings such as the integration method integration order or axisymmetry assumption using these properties e method specify the integration method which can be either integration or summation CHAPTER 4 WORKING WITH MODELS data mphint2 model lt expr gt edim method method where method can be integration or summation The default uses the appropriate method for the given expression e intorder specify the integration order data mphint2 model lt expr gt edim intorder lt order gt where order is a positive integer The default value is 4 e intsurface or intvolume compute surface or volume integral for axisymmetry models data mphint2 model lt expr gt edim intsurface on data mphint2 model lt expr gt edim intvolume on Evaluating a Global Expression Evaluate a global expression with the function mphglobal To evaluate a global expression at the MATLAB prompt call the function mphglobal as in this command d1 dn mphglobal model ecl en where e1 enare the COMSOL global expressions to evaluate The output values d1 dn are returned as a Px double array with P the length of inner parameters SPECIFY THE EVALUATION DATA The function mphglobal supports the following properties to set the data o
57. ks Constraint Group Ei A Sort by Type Dynamic Help FL fox E aha aa si g FA n Aa Analytic Interpolation Piecewise External Gaussian Pulse MATLAB Ramp Random Rectangle Step Triangle Waveform Elevation DEM Image The settings window of the MATLAB node has these sections Functions where you declare the name of the MATLAB functions and their arguments e Derivatives where you define the derivative of the MATLAB functions with respect to all function arguments e Plot Parameters where you can define the limit of the arguments value in order to display the function in the COMSOL Desktop Graphics window THE MATLAB FUNCTION FEATURE NODE 179 180 CHAPTER 5 DEFINING THE MATLAB FUNCTION This figure illustrates the MATLAB settings window f MATLAB gt i Model Library Material Browser nf Plot 4 Create Plot a v Functions Clear Functions E Clear functions automatically before solving Function Arguments tpw Function Arguments gt Derivatives gt Plot Parameters Under Functions define the function name and the list of the function arguments In the table columns and rows enter the Function name and the associated function Arguments The table supports multiple function definitions Define several functions in the same table or add several MATLAB nodes as you prefer PLOTTING THE FUNCTION Click the Plot button to di
58. mphload transport_and_asorption mph Evaluate the concentration along boundary 5 at t 2 s list 0 1e 3 0 1 0 2 0 1 0 9 0 9 1e 3 1 c y mphinterp model c y coord list edim 1 selection 5 t 2 Load stresses_in_pulley mph from the Model Library model mphload stresses_in_pulley mph Evaluate the von Mises effective stress at the cut point data set cptl mises n mphinterp model solid mises n datset cpt1 mpheval mphevalpoint mphglobal mphinputmatrix 225 mphload 226 Purpose Syntax Description Example See also Load a COMSOL model MPH file model mphload filename model mphload filename ModelObjectName model mphload filename ModelObjectName history model filename mphload filename ModelObjectName model mphload filename loads a COMSOL model object saved with the name filename and assigns the default name Model in the COMSOL server model mphload filename ModelObjectName loads a COMSOL model object and assigns the name Model0bjectName in the COMSOL server model mphload filename ModelObjectName history turns on history recording model filenameloaded mphload filename ModelObjectName also returns the full file name filenameloaded of the file that was loaded If the model name is the same as a model that is currently in the COMSOL server the loaded model overwrites the existing one Note that
59. output str is a MATLAB structure with the following fields e dimension the space dimension of the geometry entity selected e geom the tag of the geometry node used in the selection e entities the list of the entity indexes listed in the selection and e isGlobal Boolean value to indicate if the selection is global or not CHAPTER 4 WORKING WITH MODELS Handling Errors and Warnings In this section e Errors and Warnings e Using MATLAB Tools To Handle COMSOL Exceptions e Displaying Warnings and Errors in the Model Errors and Warnings COMSOL Multiphysics reports these types of problems e Errors which prevents the program from completing a task and e Warnings which are problems that do not prevent the completion ofa task but that might affect the accuracy or other aspects of the model For both errors and warnings a message is stored in a separate node located just below the problematic model feature node In case of errors a Java Exception is thrown to MATLAB which also breaks the execution of the script Using MATLAB Tools To Handle COMSOL Exceptions When running a model that returns an error in MATLAB the execution of the script is automatically stopped You can use MATLAB tools to handle exceptions and prevent the script from breaking Use the try and catch MATLAB statements to offer alternatives to a failed model In a loop for example use the try and catch statements to continue to the next
60. parameter values for parametric problems respectively In case of multiple expression if the unit property is defined with a string the same unit is used for both expressions To use different units set the property with a cell array In case of inconsistent unit definition the default unit is used instead Solnum is used to select the solution number when a parametric eigenvalue or time dependent solver has been used Outersolnum is used to select the outer solution number when a parametric sweep has been used in the study step node Load fluid_valve mph from the Model Library model mphload fluid_valve mph Evaluate the global expression u_up for each time step u_up mphglobal model u_up Evaluate the global expression u_up at 0 8 sec u_up mphglobal model u_up t 0 8 Evaluate the expressions u_up and u_down at the last solution number u_up u_down mphglobal model u_up u_down solnum end Evaluate the expressions u_up in mm 2 s and u_down in cm 2 s u_up u_down mphglobal model u_up u_down unit mm 2 s cm 2 s mpheval mphevalpoint mphinputmatrix mphinterp CHAPTER 6 COMMAND REFERENCE mphimage2geom Purpose Syntax Description Example Convert image data to geometry model mphimage2geom imagedata level model mphimage2geom imagedata level converts the image contained in imagedata into a geometry which is returned in the mod
61. points You can also set the initsol property to zero which corresponds to using a null solution vector as a linearization point The default is the current solver node where the assemble node is associated For continuation time dependent or eigenvalue analyses you can set the solution number to use as a linearization point Use the solnum property str mphmatrix model lt soltag gt out out solnum lt solnum gt where lt solnum gt is an integer value corresponding to the solution number The default value is the last solution number available with the current solver configuration WORKING WITH MATRICES 143 144 See Retrieving Xmesh Information to learn how to get relation between the degrees of freedom information in the matrix system and coordinates See Also or element information EXAMPLE MPHMATRIX The following illustrates how to use the mphmatrix command to extract eliminated system matrices of a stationary analysis and linear matrix system at the MATLAB prompt The model consists of a linear heat transfer problem solved on a unit square with a 1e5 W m 2 surface heat source and temperature constraint Only one quarter of the geometry is represented in the model For simplification reasons the mesh is made of four quad elements The commands below set the COMSOL model object model ModelUtil create Model geom1 model geom create geom1 2 geom1 feature create sqi
62. quadrilateral mesh in 2D use the Map operation This operation uses a mapping technique to create the quadrilateral mesh Q Map in the COMSOL Java API Reference Guide See Also Use the EdgeGroup attribute to group the edges boundaries into four edge groups one for each edge of the logical mesh To control the edge element distribution use the Distribution attribute which determines the overall mesh density Example Creating a Structured Quadrilateral Mesh Create a structured quadrilateral mesh on a geometry where the domains are bounded by more than four edges model ModelUtil create Model geom1 model geom create geom1 2 geom1 feature create r1 Rectangle r2 geom1 feature create r2 Rectangle WORKING WITH MESHES 59 r2 set pos 1 0 c1 geom1 feature create c1 Circle c1 set r 0 5 c1 set pos 1 1 0 1 difi geom1 feature create dif1 Difference dif1 selection input set ri r2 dif1 selection input2 set c1 geom1 run dif1 meshi model mesh create mesh1 geom1 mapi mesh1 feature create map1 Map eg1 map1 feature create eg1 EdgeGroup eg1 selection set 1 eg1 selection edge1 set 1 3 eg1 selection edge2 set 2 eg1 selection edge3 set 8 eg1 selection edge4 set 4 eg2 map1 feature create eg2 EdgeGroup eg2 selection set 2 eg2 selection edge1 set 4 eg2 selection edge2 set 6 9 1
63. selection sel1 info mphgetselection model selection seli mphnavigator 210 CHAPTER 6 COMMAND REFERENCE mphgetu Purpose Syntax Description Example Return solution vector U mphgetu model U Udot mphgetu model U mphgetu model returns the solution vector U for the default solution data set U Udot mphgetu model returns in addition Udot which is the time derivative of the solution vector This syntax is available for a time dependent solution only For a time dependent and parametric analysis type the last solution is returned by default For an eigenvalue analysis type the first solution number is returned by default The function mphgetu accepts the following property value pairs TABLE 6 5 PROPERTY VALUE PAIRS FOR THE MPHGETU COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Solname String Auto Solver node tag Solnum Positive integer Auto Solution for evaluation vector Type String Sol Solution type Matrix off on on Store as matrix if possible The Solname property set the solution data set to use associated with the defined solver node Type is used to select the solution type This is So1 by default The valid types are Sol main solution Reacf reaction force Adj adjoint solution Fsens functional sensitivity and Sens forward sensitivity If Solnum is a vector and the result has been obtained with the same mesh then the s
64. selection node is a Ball or Box selection the ball or box used in the selection can be displayed with this command mphviewselection model lt geomtag gt lt seltag gt showselector on 96 CHAPTER 3 BUILDING MODELS Computing the Solution This section describes the commands to use to compute the solution at the MATLAB prompt How to set up and run a study node but also how to set manual solver sequence This includes the following paragraphs e The Study Node e The Solver Sequence Syntax e Run the Solver Sequence e Adding a Parametric Sweep e Adding a Job Sequence e Plot While Solving e Solver Features in the COMSOL Multiphysics Reference Guide e Solver in the COMSOL Java API Reference Guide a See Also Oo The links to features described outside of this user guide do not work in the PDF only from within the online help Important The Study Node A study node holds the nodes that define how to solve a model These nodes are divided into three broad categories e Study steps which determines overall settings suitable for a certain study type e Solver sequence e Job configurations for distributed parametric jobs batch jobs and cluster computing COMPUTING THE SOLUTION 97 98 CHAPTER 3 a e The Study Node in the COMSOL Reference Guide See Also Create a study node by using the syntax model study create lt studytag gt where studytag is a string that is used to
65. solid1 ins1 cib1 init1 and os1 These are the default features that come with the Heat Transfer in Solids interface The first feature solid1 consists of the heat balance equation Confirm this by entering gt gt solid phys feature solid1 ans Type Heat Transfer in Solids Tag solidi You can modify the settings of the solid1 feature node for example to manually set the material property To change the thermal conductivity to 400 W m K enter solid set k_mat 1 solid set k 400 userdef The Heat Transfer in Solids interface contains features you can use to specify domain 3 or boundary settings For example to add a heat source of 10 W m in the study domain enter the commands hs phys feature create hs1 HeatSource 3 hs selection set 1 hs set Q 1 1e5 To create a temperature boundary condition on boundaries 3 5 and 6 enter temp phys feature create temp1 TemperatureBoundary 2 temp selection set 3 5 6 temp set TO 1 300 K Then add a mesh and a study feature and compute the solution model mesh create meshi geom1 std model study create std1 std feature create stat Stationary std run To visualize the solution first create a 3D surface plot group which is displayed in a MATLAB figure with the function mphplot pg model result create pgi PlotGroup3D pg feature create surf1 Su
66. specify the phase in degrees data mphglobal model lt expr gt phase lt phase gt where lt phase gt is a double value OUTPUT FORMAT The function mphglobal also supports other output formats To extract the unit of the evaluated expression define an extra output variable data unit mphglobal model lt expr gt with unit is a 1xN cell array where N is the number of expression to evaluate Include the imaginary part in the data evaluation with the property complexout data mphglobal model lt expr gt complexout on OTHER EVALUATION PROPERTIES Set the unit property to specify the unit of the evaluation data mphglobal model lt expr gt unit lt unit gt where lt unit gt is a cell array with the same length as lt expr gt To not use complex value functions with real inputs use the property complexfun data mphglobal model lt expr gt complexfun off The default value uses complex value functions with real inputs Use the property matherr to return an error for undefined operations or expressions data mphglobal model lt expr gt matherr on CHAPTER 4 WORKING WITH MODELS Evaluating a Global Matrix mphevalglobalmatrix evaluates the matrix variable such as S parameters in a model with several ports activated as a parametric sweep and a frequency domain study To evaluate the global matrix associated to the expression lt expr gt enter the command M mphevalglo
67. support comsol com An automatic notification and case number is sent to you by email HELP AND DOCUMENTATION 13 COMSOL WEB SITES Main Corporate web site www comsol com Worldwide contact information www comsol com contact Technical Support main page www comsol com support Support Knowledge Base Product updates www comsol com support knowledgebase www comsol com support updates COMSOL User Community www comsol com community Typographical Conventions All COMSOL user s guides use a set of consistent typographical conventions that make it easier to follow the discussion understand what you can expect to see on the graphical user interface GUI and know which data must be entered into various data entry fields In particular these conventions are used throughout the documentation CONVENTION EXAMPLE text highlighted in blue boldface font italic font Forward arrow symbol gt Click text highlighted in blue to go to other information in the PDF When you are using the online help desk in COMSOL Multiphysics these links also work to other modules model examples and documentation sets A boldface font indicates that the given word s appear exactly that way on the COMSOL Desktop or for toolbar buttons in the corresponding tip For example the Model Builder window 7 is often referred to and this is the window that contains the model tree As another example the i
68. the property t pd mpheval model lt expr gt t lt time gt where lt time gt is a double array The default value corresponds to all the stored time steps e phase specify the phase in degrees pd mpheval model lt expr gt phase lt phase gt where lt phase gt is a double value e pattern use Gauss point evaluation pd mpheval model lt expr gt pattern gauss The default evaluation is performed on the Lagrange points OUTPUT FORMAT The function mpheval returns a structure in the MATLAB workspace You can specify other output data formats CHAPTER 4 WORKING WITH MODELS To only obtain the data evaluation as a double array set the property dataonly to on pd mpheval model lt expr gt dataonly on Include the imaginary part in the data evaluation with the property complexout pd mpheval model lt expr gt complexout on SPECIFY THE EVALUATION QUALITY Define function settings to specify the evaluation quality e refine specify the element refinement for evaluation pd mpheval model lt expr gt refine lt refine gt where lt refine gt is a positive integer The default value is 1 which set the simplex mesh identical to the geometric mesh e smooth specify the smoothing method to enforce continuity on discontinuous data evaluation pd mpheval model lt expr gt smooth smooth where smooth is either none everywhere or internal de
69. this command d1 dn mphint2 model e1 en edim where e1 en are the COMSOL expressions to integrate The values d1 dn are returned as a 1xP double array with P the length of inner parameters edim is the integration dimension which can be line surface volume or an integer value that specifies the space dimension 1 2 or 3 SPECIFY THE INTEGRATION DATA The function mphint2 supports the following properties to set the data of the evaluation to perform e dataset specify the solution data set to use in the integration data mphint2 model lt expr gt edim dataset lt dsettag gt lt dsettag gt is the tag of a solution data set The default value is the current solution data set of the model e selection specify the integration domain data mphint2 model lt expr gt edim selection lt seltag gt where lt seltag gt is the tag of a selection node to use for the data evaluation lt seltag gt can also be a positive integer array that corresponds to the domain index list The default selection is all domains where the expression is defined If the evaluation point does not belong to the specified domain selection the output value is NaN e solnum specify the inner solution number for data evaluation Inner solutions are generated for the following analysis types time domain frequency domain eigenvalue or stationary with continuation parameters EXTRACTING RESULTS 127 128
70. using Tinput as an input variable and the probe mod1 ppb1 as an output variable M mphstate model sol1 out Mc MA MB C D input TO output mod1 ppb1 Compute the state space system with the extracted matrices TO 273 15 Tinput 1273 15 T0 opt odeset mass M Mc func t x M MA x M MB Tinput t x ode23s func 0 10 190 zeros size M MA 1 1 opt y M C x y yt T0 Compare the solution computed with the state space system and the one computed with COMSOL plot t y hold on Tnum mphinterp model T coord 0 28 0 38 t t plot t Tnum r WORKING WITH MATRICES 153 1400 1200 1000 800 600 400 200 0 20 40 60 80 100 120 140 160 180 200 Figure 4 1 Temperature distribution computed with the state space system blue line and COMSOL Multiphysics red marker 154 CHAPTER 4 WORKING WITH MODELS Extracting Solution Information and Solution Vector In this section e Obtaining Solution Information e Extracting Solution Vector Obtaining Solution Information Get the solution object information with the function mphsolinfo Specify only the model object to obtain the information of the default solution object info mphsolinfo model The function mphsolinfo replaces the function mphgetp Note SPECIFYING THE SOLUTION OBJECT To retrieve the information of a specific solution object set the solname property with
71. viewing the Model Library Syntax mphmodellibrary Description mphmodellibrary starts a GUI to visualize and access the example model available in the COMSOL Model Library The model MPH file can be loaded in MATLAB and the model documentation PDF file is accessible directly Models that are specific to LiveLink for MATLAB also contains the script M file r 2 mphmodellibrary Model Library COMSO bal Models v Only show LiveLink for MATLAB COMSOL Model Library LiveLink for MATLAB Tutorial Models a busbar_Ilsw_llmatlab m f domain activation_llmatlab m i E domain vation_limatlab mph 9 h_nat m homogenization_limatlabsm homogenization_limatlabsmph k foam m sk foam_dT m ee ie en ae gt m Domain Activation and Deactivation This model of a time dependent heat transfer problem implements heating from alternating regions by using domain activation and deactivation 240 CHAPTER 6 COMMAND REFERENCE mphnavigator Purpose Syntax Description Example Graphical User Interface for viewing the COMSOL model object mphnavigator mphnavigator modelvariable mphnavigator opens the Model Object Navigator which is a graphical user interface that can be used to navigate the model object and to view the properties and methods of the nodes in the model tree The GUI requires that the COMSOL objest is stored in
72. 0 eg2 selection edge3 set 7 eg2 selection edge4 set 5 meshi1 run mphmesh model 0 02 04 06 08 1 12 14 16 18 2 Figure 3 6 Structured quadrilateral mesh right and its underlying geometry The left hand side plot in Figure 3 6 is obtained with this command mphgeom model geom1 edgelabels on 60 CHAPTER 3 BUILDING MODELS The EdgeGroup attributes specify that the four edges enclosing domain 1 are boundaries 1 and 3 boundary 2 boundary 8 and boundary 4 For domain 2 the four edges are boundary 4 boundary 5 boundary 7 and boundaries 9 10 and 6 BUILDING A MESH INCREMENTALLY To build meshes in a step by step fashion create selections for the parts of the geometry that you want to mesh in each step as in this example model ModelUtil create Model1 geom1 model geom create geom1 2 geom1 feature create r1 Rectangle geom1 feature create c1 Circle unit geom1 feature create uni1 Union unit selection input set c1 r1 geom1 runCurrent deli geom1 feature create deli Delete del1 selection input init 1 del1 selection input set unii 8 geom1 run del1 meshi model mesh create meshi geom1 dis1 mesh1 feature create disi Distribution dis1 selection set 2 4 disi set type predefined dis1 set method geometric dis1 set elemcount 20 dis1 set reverse on disi set elemr
73. 1 geom1 model geom create geomi 2 geom1 feature create sqi Square geom1 run mesh1 model mesh create meshi geom1 mesh1 feature create ftrii FreeTri mesh1 feature feature size set hmax 0 5 mesh1 run ftri1 WORKING WITH MESHES 77 mphmesh model To get the mesh data information enter meshstats meshdata mphmeshstats model meshdata vertex 2x12 double elem 2x8 int32 3x14 int32 05 7 11 elementity 8x1 int32 14x1 int32 4x1 int32 The mesh node coordinates are stored in the vertex field vtx meshdata vertex vtx Columns 1 through 7 0 0 5000 0 3024 0 0 6314 1 0000 0 3511 0 0 0 3023 0 5000 0 3632 0 0 6397 Columns 8 through 12 0 0 6730 1 0000 0 5000 1 0000 1 0000 0 6728 0 5000 1 0000 1 0000 In the elem field the element information is retrieved such as the node indices using a 0 based connected to the elements tri meshdata elem 2 tri Columns 1 through 5 0 3 1 1 6 78 CHAPTER 3 BUILDING MODELS 1 0 4 5 3 2 2 2 4 2 Columns 6 through 10 6 7 6 5 9 2 3 4 9 8 4 6 8 4 4 Columns 11 through 14 10 10 9 11 7 6 11 10 6 8 8 8 In the above command observe that element number 1 is connected to nodes 1 2 and 3 and element number 2 is connected to nodes 4 1 and 3 Now create manually a mesh using a data distribution generated in MATLAB Enter the command x y meshgrid 0 0 5 1 0 0 5 1 X reshape
74. ATLAB Java heap size to be able to manipulate the model object and extract data at the MATLAB prompt See Improving Performance for Large Models CHAPTER 2 GETTING STARTED CONNECTING MATLAB AND THE COMSOL SERVER ON DIFFERENT COMPUTERS EI This operation requires the specific license type called Floating Network License FNL Note To connect MATLAB and a COMSOL server that are running on different computers specify in the function mphstart the IP address of the computer where the COMSOL server is running mphstart lt ipaddress gt lt portnumber gt IMPORTING THE COMSOL CLASS Once MATLAB and the COMSOL server are manually connected import the COMSOL class by entering the following command at the MATLAB prompt import com comsol model import com comsol model util Disconnecting MATLAB and the COMSOL Server To disconnect MATLAB and the COMSOL server run the command below at the MATLAB prompt ModelUtil disconnect Changing the MATLAB Version The path of the MATLAB version connected to COMSOL is defined during the initial COMSOL installation The MATLAB root path can be changed using the preferences file In the COMSOL Desktop go to the Options menu and select Preferences 2 In the Preferences window go to LiveLink products 3 Set the MATLAB root directory path in the MATLAB installation folder field 4 Windows OS users also need to click Register MATLAB as COM Server button otherwise the speci
75. Delete feature For example to remove the structured mesh from domain 2 along with the adjacent edge mesh on edges 3 and 4 and replace it with an unstructured quad mesh enter these commands deli mesh1 feature create del1 Delete del1 selection geom geom1 2 set 2 del1 set deladj on frqi meshi feature create frq1 FreeQuad frqi selection geom geomi1 2 set 2 mesh1 run BUILDING MODELS Q For further details on the various commands and their properties see the See Also COMSOL Java API Reference Guide REVOLVING A MESH BY SWEEPING Create 3D volume meshes by extruding and revolving face meshes with the Sweep feature Depending on the 2D mesh type the 3D meshes can be hexahedral brick meshes or prism meshes Example Revolved Mesh Create and visualize a revolved prism mesh as follows model ModelUtil create Model geom1 model geom create geomi 3 wp1 geom1 feature create wp1 WorkPlane wp1 set planetype quick wp1 set quickplane xy c1 wo1 geom feature create c1 Circle c1 set pos 2 0 revi geom1 feature create rev1 Revolve revi1 set angle2 60 set angle1 60 rev1 selection input set wp1 geom1 run rev1 mesh1 model mesh create meshi1 geom1 mesh1 feature create ftrii FreeTri mesh1 feature ftrii1 selection geom 2 mesh1 feature ftrii selection set 2 mesh1 runCurre
76. El The progress bar is not supported on Mac OS X Note CHAPTER 3 Loading and Saving a Model LOADING A MODEL AT THE MATLAB PROMPT To load an existing model saved as an MPH file use the function mphload For example to load the Busbar model from the Model Library enter model mphload busbar mph This creates a model object Model on the COMSOL server that is accessible using the MATLAB variable model BUILDING MODELS If there is already a model object Model linked to a MATLAB variable mode1 load the model using a different name with the command model2 mphload busbar mph Model2 When using the function mphload the model history is automatically disabled to prevent large history information when running a model in a loop To turn model history on use the function mphload model mphload busbar mph history The history recording can be useful when using the COMSOL Desktop All the operations are then stored in the saved model M file SAVING A MODEL OBJECT Use the function mphsave to save the model object linked to the MATLAB object model mphsave model filename If the filename specified filename does not provide a path the file is saved relative to the local MATLAB path The file extension determines the format to use mph m or java Alternatively use the save method model save filename If filename does not provide a path the file is saved relative to the local COMSOL
77. GB array 0 6 0 6 0 6 Color for face Facecolorselected RGB array 1 0 0 Color for selected face Facelabels on off off Show face labels Facelabelscolor Char RGB b Color for face labels array Facemode on off on Show faces Geommode on off on Show entire geometry Marker Vertex marker Markercolor Char RGB b Color for vertex array marker Markercolorselected Char RGB r Color for selected array vertex marker 259 mphviewselection TABLE 6 25 PROPERTY VALUE PAIRS FOR THE MPHVIEWSELECTION FUNCTION PROPERTY VALUE DEFAULT DESCRIPTION Markersize Int 12 Font size of marker Parent Double Parent axis Renderer Opengl opengl Set the rendering zbuffer method Selection String Set selection name or Positive entity number integer array Selectoralpha Double 0 25 Set selector transparency value Selectorcolor RGB array 0 0 1 Color for selected marker Showselector on off on Show Selector Vertexlabels on off off Show vertex labels Vertexlabelscolor Char RGB r Color for vertex array labels Vertexmode on off off Show vertices Example Load busbar mph from the Model Library model mphload busbar Plot boundary number 3 using a yellow color mphviewselection model geom1 3 entity boundary facecolorselected 1 1 0 facealpha 0 5 Plot edge 1 to 9 in green color hold on mphviewselection model geom1 1 8 geommode off entity edge edgecolorselected 0 1
78. HES 67 68 CHAPTER 3 Figure 3 11 Boundary layer mesh based on an unstructured triangular mesh It is also possible to insert boundary layers in an existing mesh Use the following meshing sequence with the geometry sequence from the previous example b11 active false fqi mesh1 feature create fqi FreeQuad fqi selection set 1 mphmesh model bli mesh1 feature create bl2 BndLayer b11 feature create blp2 BndLayerProp b11 feature blp2 selection set 2 3 5 6 7 8 meshi1 run BUILDING MODELS mphmesh model Figure 3 12 Initial unstructured quad mesh left and resulting boundary layer mesh right REFINING MESHES Given a mesh consisting only of simplex elements lines triangles and tetrahedra you can create a finer mesh using the feature Refine Enter this command to refine the mesh mesh1 feature create ref1 Refine By specifying the property tri either as a row vector of element numbers or a 2 row matrix the elements to be refined can be controlled In the latter case the second row of the matrix specifies the number of refinements for the corresponding element The refinement method is controlled by the property rmethod In 2D its default value is regular corresponding to regular refinement in which each specified triangular element is divided into four triangles of the same shape Setting rmethod to longest gives longest edge refinemen
79. I Reference Guide Example Creating a 2D Mesh with Triangular Elements Generate a triangular mesh of a unit square model ModelUtil create Model 54 CHAPTER 3 BUILDING MODELS geom1 model geom create geom1 2 geom1 feature create r1 Rectangle meshi model mesh create meshi geom1 ftril meshi feature create ftril FreeTri mesh1 run mphmesh model Figure 3 1 Default mesh on a unit square The default size feature is generated with the property hauto set to 5 that is mesh1 feature size set hauto 5 To override this behavior set hauto to another integer Override this by setting specific size properties for example making the mesh finer than the default by specifying a maximum element size of 0 02 mesh1 feature size set hmax 0 02 mesh1 run mphmesh model This value corresponds to 1 50 of the largest axis parallel distance whereas the default value is 1 15 WORKING WITH MESHES 55 56 CHAPTER 3 Figure 3 2 Fine mesh maximum element size 0 02 Sometimes a nonuniform mesh is desirable Make a mesh that is denser on the left side by specifying a smaller maximum element size only on the edge segment to the left edge number 1 mesh1 feature size set hauto 5 size1 ftril feature create size1 Size size1 set hmax 0 02 size1 selection geom geom1 1 size1 selection set 1 mesh1 run mphmesh model BU
80. ILDING MODELS 0 9 0 8 0 7 0 6 0 5 0 4 0 3 0 2 0 1 Figure 3 3 Nonuniform mesh The Free Meshing Method The default method to generate free triangle meshes in 2D is based on an advancing front algorithm To switch to a Delaunay algorithm use the value de1 for the method property Start by creating a geometry model geom1 geom1 ModelUtil create Model model geom create geom1 2 feature create r1 Rectangle c1 geom1 feature create c1 Circle c1 set r 0 5 co1 geom1 feature create co1 Compose co1 selection input set c1 r1 co1 set formula ri c1 geom1 mesh1 ftril ftril runAll model mesh create mesh1 geom1 meshi feature create ftrii Freetri set method del WORKING WITH MESHES 57 mesh1 run mphmesh model mesh1 Figure 3 4 Mesh created with the Delaunay method Example Creating a 2D Mesh with Quadrilateral Elements To create an unstructured quadrilateral mesh on a unit circle enter model ModelUtil create Model geom1 model geom create geom1 2 geom1 feature create c1 Circle mesh1 model mesh create mesh1 geom1 mesh1 feature create ftrii FreeQuad mesh1 run mphmesh model 58 CHAPTER 3 BUILDING MODELS 0 8 0 6 0 4 0 2 0 2 0 4 0 6 0 8 Figure 3 5 Free quad mesh CREATING STRUCTURED MESHES To create a structured
81. IPTION out Cell array of List of matrices to assemble strings Initmethod init sol sol Use linearization point Initsol string zero Active Solution to use for solver tag linearization Solnum Positive auto Solution number integer auto The following values are valid for the out property Property Value Pairs for the property out PROPERTY EXPRESSION DESCRIPTION out K Stiffness matrix L Load vector M Constraint vector N Constraint Jacobian D Damping matrix E Mass matrix NF Constraint force Jacobian NP Optimization constraint Jacobian MP Optimization constraint vector MLB Lower bound constraint vector MUB Upper bound constraint vector 227 mphmatrix 228 Example Property Value Pairs for the property out PROPERTY EXPRESSION DESCRIPTION Ke Eliminated stiffness matrix Le Eliminated load vector De Eliminated damping matrix Ec Eliminated mass matrix Null Constraint null space basis Nullf Constraint force null space matrix ud Particular solution ud uscale Scale vector Requires the Optimization Module Note that the assembly of the eliminated matrices uses the current solution vector as scaling method To get the unscaled eliminated system matrices it is required to set the scaling method to none in the variables step of the solver configuration node The load vector is assembled using the current solution available as linearization point unless the initmethod property
82. LAB Function from the COMSOL Desktop 18 The Client Server Architecture LiveLink for MATLAB uses the client server mode to connect COMSOL Multiphysics and MATLAB When starting COMSOL with MATLAB two processes are started a COMSOL server and the MATLAB desktop The MATLAB process is a client connected to the COMSOL server using a TCP IP communication protocol The COMSOL Desktop is not involved Note The first time you start COMSOL with MATLAB you are requested to provide login information This information is stored in the user preferences file and is not requested for later use of COMSOL with MATLAB The same login information may be used when exchanging the model object between the COMSOL server and the COMSOL Desktop The communication between the COMSOL server and MATLAB is established by default using port number 2036 If this port is in use port number 2037 is used instead and so on You can manually specify the port number See COMSOL Server Li Commands in the COMSOL Multiphysics Installation and Operations See Also Guide for more information on the COMSOL server start up properties 0 The links to features described outside of this user guide do not work in the PDF only from within the online help Important To locate and search all the documentation for this information in COMSOL select Help gt Documentation from the main menu and either 7 i enter a search term or look under a spe
83. MATLAB searches for the model on the MATLAB path if an absolute path is not supplied mphload turns off the model history recording by default unless the property history is used The extension mph can be omitted Load transport_and_adsorption mph from the Model Library model mphload transport_and_asorption mph Load stresses_in_pulley mph without specifying the mph extension model mphload stresses_in_pulley Load the model from MyMode1 mph with the path specified model mphload PATH MyModel mph Load ef fective_diffusivity mph from the Model Library and return the file name model filename mphload effective _diffusivity mph mphsave CHAPTER 6 COMMAND REFERENCE mphmatrix Purpose Syntax Description Get model matrices str mphmatrix model soltag Out mphmatrix model soltag Out A returns a MATLAB structure str containing the matrix A assembled using the solver node soltag and str accessible as str A A being taken from the Out property list str mphmatrix model soltag fname Out A B returns a MATLAB structure str containing the matrices A B assembled using the solver node solname and accessible as str A and str B A and B being taken from the Out property list The function mphmatrix accepts the following property value pairs TABLE 6 12 PROPERTY VALUE PAIRS FOR THE MPHMATRIX COMMAND PROPERTY EXPRESSION DEFAULT DESCR
84. MATRICES 151 152 To extract sparse matrices set the property sparse to on str mphstate model lt soltag gt input lt input gt output lt output gt out out sparse on To keep the state space feature node set the property keepfeature to on str mphstate model lt soltag gt input lt input gt output lt output gt out out keepfeature on 5 SET LINEARIZATION POINTS mphstate uses linearization points to assemble the state space matrices The default linearization point is the current solution provided by the solver node to which the state space feature node is associated If there is no solver associated to the solver configuration a null solution vector is used as a linearization point j The linearization point needs to be a steady state solution Note You can manually select which linearization point to use Use the initmethod property to select a linearization point str mphstate model lt soltag gt input lt input gt output lt output gt out out initmethod method where method corresponds to the type of linearization point the initial value expression init or a solution sol To set the solution to use for the linearization point use the property initsol str mphstate model lt soltag gt input lt input gt output lt output gt out out initsol lt initsoltag gt where lt initsoltag gt is the solve
85. MPH files created in COMSOL Multiphysics 3 5a and later versions in COMSOL Multiphysics 4 3a When going from version 3 5a to version 4 a major revision was made to the MATLAB interface This revision was made to reflect changes made to the new user interface and to support parameterized geometry operations As a result a new MATLAB interface syntax is used in today s version of COMSOL Multiphysics and its add on product LiveLink for MATLAB In order to assist in the conversion process a special compatibility mode was created to facilitate the new syntax This compatibility mode together with the LiveLink for MATLAB function mphv4 is no longer supported as of COMSOL Multiphysics 4 3 If you wish to convert a model defined with an M file created with version 3 5a to the version 4 3a format we recommend the following procedure l Run the M file using COMSOL Multiphysics 3 5a and save the model using flsave as an MPH file 2 Load the model into COMSOL Multiphysics 4 3a and verify that the model settings have been translated correctly In addition verify that the model can be meshed and solved 3 Select File gt Reset history 4 Select File gt Save as Model M file The saved M file can now be tested if you start the current version of COMSOL Multiphysics with MATLAB If you have any problems with this conversion process please contact COMSOL s technical support team at support comsol com or your local COMSOL representative
86. MSOL Multiphysics ee Search Ce V Name F Expression F Description Type Name Expression Description Type Path 1 _ F_const 96485 3399 C mol Faraday constant Varnames model variable iexpr1 a 2 G_const 6 67428E 11 m 3 kg s 2 Gravitational constant Varnames model variable iexpr1 3 Heat_prict Tag model elem Heat_prict 4 j Field model physics jh SEDL cm Varnames model param 6 _ N_A_const 6 02214179E23 1 mol Avogadro constant Varnames model variable iexpr1 7 R_const 8 314472 J K mol Universal gas constant Varnames model variable iexpr1 8 it Field model physics jh 9 NV Field model physics jh 10 V_m_const 0 022413996 m 3 mol Molar volume of idealgas Varnames model variable iexpr1 11 _ Vtot 20 mV Varnames model param 12 Z0_const root mu0_const root c_const Characteristic impedance of Varnames model variable iexpr1 13 _ aDef Advanced Tag model sol sol1 feature s feature a 14 _ alpha_const 0 0072973525376 Fine structure constant Varnames model variable iexpr1 15 b_const 0 0028977685 m K Wien displacement law cons Varnames model variable iexpr1 4 m Copy Close d The table has the following for each entry the name of the expression e expression as it is set in the property value e description if there is one set for the expression e type of the expression and the e path in the model object The Search section has a searching tool to
87. Multiphysics User s Guide See Also T The links to features described outside of this user guide do not work in the PDF only from within the online help Important The Physics Interface Syntax Create a physics interface instance using the syntax model physics create lt phystag gt physint lt geomtag gt where lt phystag gt is a string that identifies the physics interface Once defined you can always refer to a physics interface or any other feature by its tag The string physint is the constructor name of the physics interface To get the constructor name the best way is to create a model using the desired physics interface in the GUI and save the model as an M file The string lt geomtag gt refers to the geometry where you want to specify the interface To add a feature to a physics interface use the syntax model physics lt phystag gt feature create lt ftag gt operation where the lt phystag gt string refers to a physics interface lt ftag gt is a string that you use to refer to the operation To set a property to a value in a operation enter MODELING PHYSICS 8l 82 model physics lt phystag gt feature lt ftag gt set property lt value gt where lt ftag gt is the string that identifies the feature Q There are alternate syntaxes available See model physics in the See Also COMSOL Java API Reference Guide CHAPTER 3 To disable or remove a feature node use th
88. The t property is available only for time dependent problems If Solnum is provided the solutions indicated by the indices provided with the Solnum property are used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated For time dependent problems the variable t can be used in the expressions ei The value of t is the interpolation time when the property t is provided and the time for the solution when Solnum is used Similarly Lambda and the parameter are COMMAND REFERENCE mphinterp Example See also available as eigenvalues for eigenvalue problems and as parameter values for parametric problems respectively In case of multiple expression if the unit property is defined with a string the same unit is used for both expressions To use different units set the property with a cell array In case of inconsistent unit definition the default unit is used instead Solnum is used to select the solution number when a parametric eigenvalue or time dependent solver has been used Outersolnum is used to select the outer solution number when a parametric sweep has been used in the study step node Load heat_convection_2d mph from the Model Library model mphload heat_convection_2d mph Compute the temperature T at the center of the domain T mphinterp model T coord 0 3 0 5 Load transport_and_adsorption mph from the Model Library model
89. To create a player feature node to the model enter the command model result export create lt playtag gt Player Then associate the player with an existing plot group by setting the plot group property model result export lt playtag gt set plotgroup lt pgtag gt where lt pgtag gt refers to the plot group which is animated in the player The default frame number used to generate the animation is 25 you can also specify the number of frame with the command model result export lt playtag gt set maxframe lt maxnum gt where lt maxnum gt is a positive integer value that corresponds to the maximum number of frames to generate with the player Use the run method to generate the player model result export lt playtag gt run BUILDING MODELS Working With Models This section introduces you to the functionality available for LiveLink for MATLAB including the wrapper functions and the MATLAB tools that can be used and combined with a COMSOL model object In this chapter e Using MATLAB Variables in Model Settings e Extracting Results e Running Models in a Loop e Running Models in Batch Mode e Working with Matrices e Extracting Solution Information and Solution Vector e Retrieving Xmesh Information e Navigating the Model e Handling Errors and Warnings e Improving Performance for Large Models e Creating a Custom GUI e COMSOL 3 5a Compatibility 113 114 Using MATLAB Variables in Mod
90. Tools Use MATLAB tools such as for or while statements to run your model in a loop The COMSOL API Java commands can be included in scripts using MATLAB commands To evaluate such a script you need to have MATLAB connected to a COMSOL server To run a model in a loop you do not need to run the entire model M file commands from scratch It is recommended to load a COMSOL model in MATLAB and run the loop only over the desired operations The COMSOL model is automatically updated when running the study node RUNNING MODELS IN A LOOP 137 138 You can run a Model M file from scratch if you need for instance to generate the geometry in loop The model run inside a MATLAB loop is not automatically saved Make sure to save the model at each iteration Use the command mphsave to save your model object If you are not interested in saving the entire E model object at each iteration you can extract data and store it in the Note MATLAB workspace See Extracting Results to find the most suitable function to your model When running loops in MATLAB the iteration progress is entirely taking care by MATLAB only the COMSOL commands are executed in the COMSOL server You can generate as many nested loops your modeling requires and combine the loop with other MATLAB conditional statement such as if and switch or error handling statement such as try catch Break the loop with break or jump to the next loop iteration with continue
91. X 1 9 Y reshape Y 1 9 coord X Y The node distribution obtained with this command corresponds to the mesh in Figure 3 18 0 1 Io 0 2 04 4 06 0 8 17 Figure 3 18 Mesh with elements bold and nodes italic indices WORKING WITH MESHES 79 80 CHAPTER 3 Table 3 1 lists the nodes and element connectivity in the mesh TABLE 3 1 ELEMENT AND NODES CONNECTIVITY ELEMENT NODES l 1 4 5 2 1 2 5 3 2 5 6 4 2 3 6 5 4 7 8 6 4 5 8 7 5 8 9 8 5 6 9 To create the elements and nodes connectivity information use the command new_tri new_tri new_tri new_tri new_tri new_tri new_tri new_tri ONOaBRWND BRRWW 00 an ONM ARH WwW OOANNaAAP A Assign the element information node coordinates and elements connectivity information geom2 mesh2 mesh2 mesh2 mesh2 into a new mesh Use the method createMesh to create the new mesh model geom create geom2 2 model mesh create mesh2 geom2 data setElem tri new_tri data setVertex coord data createMesh BUILDING MODELS Modeling Physics This section describes how to set up physics interfaces in a model The physics interface defines the equations that COMSOL solves e The Physics Interface Syntax e The Material Syntax e Modifying the Equations Adding Global Equations e Defining Model Settings Using External Data File E Overview of the Physics in the COMSOL
92. _ alpha_const 0 0072973525376 Fine structure constant Varnames model variable iexpr1 15 _ b_const 0 0028977685 m K Wien displacement law cons Varnames model variable iexpr1 a m J gt cose L d See also mphgetexpressions mphnavigator 246 CHAPTER 6 COMMAND REFERENCE mphselectbox Purpose Syntax Description Example Select geometric entity using a rubberband box n mphselectbox model geomtag boxcoord entity n mphselectbox model geomtag boxcoord entity returns the indices of the geometry entities that are inside a selection domain rectangle or box This method looks only on the vertex coordinates and does not observe all points on curves and surfaces boxcoord set the coordinates of the selection domain specified as a Nx2 array where N is the geometry space dimension entity can be one of point edge boundary or domain following the entity space dimension defined below e domain maximum geometry space dimension e boundary maximum geometry space dimension 1 e edges l only for 3D geometry The function mphpselectbox accepts the following property value pairs TABLE 6 20 PROPERTY VALUE PAIRS FOR THE MPHSELECTBOX COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Adjnumber Scalar none Adjacent entity number When a model uses form an assembly more than one vertex may have the same coordinate if the coordinate is shared by separate geometric objec
93. a channel filled with water To reduce memory requirements the model is solved repeatedly on a pseudo periodic section of the channel Model Each solution corresponds to a different section and before each solution step the temperature at the outlet boundary from the previous solution is mapped to the inlet boundary e Temperature Distribution in a Vacuum Flask model name vacuum_flask_11matlab shows how to use the MATLAB function callback This example solves for the temperature distribution inside a vacuum flask with hot coffee e Electrical Heating ofa Busbar Solved with the LiveLink for SolidWorks and the LiveLink for MATLAB model name busbar_1llsw_llmatlab performs geometry optimization using COMSOL MATLAB and SolidWorks Where Do I Access the Documentation and the Model Library A number of Internet resources provide more information about COMSOL Multiphysics including licensing and technical information The electronic HELP AND DOCUMENTATION II documentation context help and the Model Library are all accessed through the COMSOL Desktop If you are reading the documentation as a PDF file on your computer the blue links do not work to open a model or content referenced in a Oo different guide However if you are using the online help in COMSOL Important Multiphysics these links work to other modules model examples and documentation sets THE DOCUMENTATION The COMSOL Multiphysics User s Guide
94. a evaluation Inner solutions are generated for the following analysis types time domain frequency domain eigenvalue or stationary with continuation parameters data mphevalpoint model lt expr gt solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index lt solnum gt can also be end to evaluate the expression for the last inner solution By default the evaluation is done using the last inner solution EXTRACTING RESULTS 125 126 e outersolnum specify the outer solution number for data evaluation Outer solutions are generated with parametric sweeps data mphevalpoint model lt expr gt outersolnum lt outersolnum gt where lt outersolnum gt is a positive integer corresponding to the outer solution index The default settings use the first outer solution for the data evaluation e To evaluate the expression data at a specific time use the property t data mphevalpoint model lt expr gt t lt time gt where lt time gt is a double array The default value corresponds to all the stored time steps Perform a data series operation with the dataseries property data mphevalpoint model lt expr gt dataseries dataseries max min rms where dataseries is either mean int std or var Depending on the property value mphevalpoint performs the following operations mean integral maximum minimum root mean square standard
95. a variable in the base workspace at the MATLAB command prompt with the name model mphnavigator modelvariable opens the model object defined with the name modelvariable in Model Object Navigator E mphnavigator Model Object Navigator COMSOL Multiphysics File Tools Settings Help au m Model Tree Rectangle 1 H coordSystem cpl H frame func 2 geom geoml wpl s z2 difl fi fi2 el r Methods Name lactive boolean lauthor String 3 lauthore COMSOL comments comments String any N detai ledgeDelete int wlolulalula jw m 1 geom geom1 feature wp1 geom feature r1 Copy dateCreated Sep 23 2011 3 36 55 PM dateModified Sep 23 2011 3 36 55 PM r Properties Property 1 base corner 2_iayer 3 layer_vector_function none 4 layer_vector_method step 5 layer_vector_numvalu 6 layer_vector_start 7_llayer_vector_step 8 _ layer_vector_stop 9 iayerbottom on 10 layereft ott 11 layername empty stringarray 12 layerold Value m Value 4 i Load busbar mph from the Model Library model mphload busbar Navigate the model object that is accessible with the variable model mphnavigator 241 mphnavigator Load ef fective_diffusivity mph from the Model Library and set the model object with the variable ef f_diff eff_diff mphload effective_ d
96. ag adds the linear system matrices and vectors stored in the MATLAB structure str to the model The system matrices is associated to the solver configuration defined with the tag soltag and solved with the solver defined with the tag soltypetag soltypetag can only be one of the following solver type Stationary Eigenvalue Time A valid structure for a stationary solver includes the following fields TABLE 6 8 PROPERTY VALUE PAIRS FOR THE MPHINT2 COMMAND FIELD NAME DESCRIPTION K Stiffness matrix L Load vector M Constraint vector N Constraint Jacobian A valid structure for a time dependent eigenvalue solver includes the following fields TABLE 6 9 PROPERTY VALUE PAIRS FOR THE MPHINT2 COMMAND FIELD NAME DESCRIPTION Stiffness matrix Load vector Constraint Jacobian K L M Constraint vector N D Damping matrix E Mass matrix There is also the possibility to include the constraint force Jacobian vector NF Once the matrix system is loaded in the model the solver configuration is set ready to run 217 mphinputmatrix 218 Example See also Note The system matrices are not stored in the model when it is saved as a MPH file or loaded into the COMSOL Desktop Load the model model_tutorial_1llmatlab mph model mphload model_tutorial_llmatlab mph Add a stationary study step and a solver configuration std1 model study create std1 std1 feature create sta
97. ages Make sure COMSOL with MATLAB is started with the graphics mode to enable plot on server To learn how to start COMSOL with MATLAB with the graphics mode see the COMSOL Multiphysics Installation and Operations Guide a See Also CHAPTER 3 To generate an animation add an Animation node to the export method model result export create lt animtag gt Animation To change the animation type use the type property according to model result export lt animtag gt set type type where type is either imageseq or movie To set the filename and finally create the animation enter model result export lt animtag gt set typefilename lt filenname gt model result export lt animtag gt run In the above typefilename depends on the type of animation export imagefilename for an image sequence giffilename for a gif animation flashfilename for a flash animation and avifilename for an avi animation BUILDING MODELS For a movie type animation it is possible to change the number of frames per second with the command model result export lt animtag gt set fps lt fps_number gt where lt fps_number gt is a positive integer that corresponds to the number of frames per second to use For all animation types you can modify the width and the height of the plot with the set method model result export lt animtag gt set width lt width_px gt model result export lt animtag g
98. ameters evaluation requires the RF module Load lossy_circulator_3d mph from the RF Module s Model Library model mphload lossy_circulator_3d mph Evaluate the S parameters matrix using the solution data set dset4 M mphevalglobalmatrix model emw SdB dataset dset4 mpheval mphinterp mphglobal 200 CHAPTER 6 COMMAND REFERENCE mphevalpoint Purpose Syntax Description Evaluate expressions at geometry vertices v1 vn mphevalpoint model e1 en v1 vn unit mphevalpoint model e1 en v1 Vvn mphevalpoint model e1 en returns the results from evaluating the expressions e1 en at the geometry vertices The values vi vn can either be a cell array or a matrix depending on the options v1 vn unit mphevalpoint model e1 en also returns the unit of all expressions e1 en in the 1xN cell array unit The function mphevalpoint accepts the following property value pairs TABLE 6 3 PROPERTY VALUE PAIRS FOR THE MPHEVAL COMMAND PROPERTY PROPERTY DEFAULT DESCRIPTION VALUE Dataset String Data set tag Dataseries none mean none The operation that is applied to the int max data series formed by the min rms evaluation std var Matrix off on on Return a matrix if possible Minmaxobj Real abs real The value being treated if Dataseries is set to max or min Outersolnum Positive 1 Solution number for parametric integ
99. and Mesh Objects Measuring Mesh Quality Getting Mesh Statistics Information Getting and Setting Mesh Data Modeling Physics The Physics Interface Syntax The Material Syntax Modifying the Equations Adding Global Equations Defining Model Settings Using External Data File Creating Selections The Selection Node Coordinate Based Selections Selection Using Adjacent Geometry Displaying Selections Computing the Solution The Study Node The Solver Sequence Syntax Run the Solver Sequence Adding a Parametric Sweep Adding a Job Sequence Plot While Solving Analyzing the Results The Plot Group Syntax Displaying The Results The Data Set Syntax The Numerical Node Syntax Exporting Data 42 44 46 52 52 53 54 73 75 76 77 8l 8l 84 85 86 88 90 90 9l 94 95 97 97 99 100 100 101 102 104 104 105 108 109 110 Chapter 4 Working With Models Using MATLAB Variables in Model Settings 114 The Set and SetIndex Methods ep heat petick a MA Using a MATLAB Function to Define Model Pisani Pi dere sey IGS Extracting Results 117 Extracting Data From Tables 2 2 2 2 ew ee ee TT Extracting Data at Node Points 118 Extracting Data at Arbitrary Points 2 2 2 122 Evaluating an Expression at Geometry Vertices 2 125 Evaluating an Integral 2 2 2 2 we ee
100. at the triangle has degenerated into a line Mesh Quality 1 _ 1 oA 24 ast d a6 28 N p 08 Figure 3 17 Visualizations of the mesh quality worst 25 left and best 25 right Getting Mesh Statistics Information Use the function mphmeshstats to get mesh statistics and mesh information where stats is a structure containing the mesh statistics information Enter stats mphmeshstats model The statistics structure contains the following fields meshtag the tag of the mesh feature isactive Boolean variable that indicates if the mesh feature is active 1 or not 0 hasproblems Boolean variable that indicates if the mesh feature contains error or warning nodes 1 or not 0 iscomplete Boolean variable that indicates if the mesh feature is built 1 or not 0 sdim the space dimension of the mesh feature types the element types present in the mesh The element type can be vertex vtx edge edg triangle tri quadrilateral quad tetrahedra tet pyramid pyr prism prism hexahedra hex The type can also be of all elements of maximal dimension in the selection a11 numelem number of elements for each element type minquality minimum element quality meanquality mean element quality qualitydistr distribution of the element quality 20 values minvolume minimum element volume area BUILDING MODELS e maxvolume maximum element volume area e volume total volume area of t
101. atement if and only if all the entries are true 1 You can replace the if statement with a single assignment to the indices retrieved from the x gt 0 6 operation and another assignment to the indices where x lt 0 6 The function could then look like this function c func2 x c x 1 6 x gt 0 6 x 2 0 3 x lt 0 6 Updating Functions If the function M file is modified using a text editor click Clear Functions to ensure the functions modifications is updated in the COMSOL model v Functions Clear Functions C Clear functions automatically before solving An alternative is to select the Clear functions automatically before solving check box Defining Function Derivatives Automatic differentiation is not supported with MATLAB functions In case the MATLAB function has Jacobian contributions its derivatives with respect to the function input arguments need to be defined By default COMSOL assumes the derivatives to be null Expand the Derivatives section to define the derivatives of the function with respect to the function arguments In the table define the derivative for each function argument In the Function column enter the function name in the Argument column enter the CALLING MATLAB FUNCTIONS argument Finally in the Function derivative column enter the expression for the corresponding derivative EI The function derivatives can also be defined by additional MATLAB functions
102. ates of the dofs nodes Nodes index of the dofs dofnames Variable names nameinds Variable names index of the dofs The nodes substructure contains the fields listed in this table FIELDS DESCRIPTION coords Nodes coordinates dofnames Variable names dofs NxM array containing the index 0 based of the dofs for each node N being the length of dofnames and M the number of nodes The element substructure contains the fields listed in this table FIELDS DESCRIPTION meshtypes List of the type of mesh available type Substructure containing the information of element of type type The type substructure lists the information for each element The possible mesh types are vtx edg quad tri quad tet hex prism and pyr The substructure type contains the fields listed in this table FIELDS DESCRIPTION localcoords Local nodes coordinates localdofcoords Local dofs coordinates localdofnames Names of the local dofs nodes Nodes index for each element dofs Dofs index for each element SPECIFY THE INFORMATION TO RETRIEVE To specify the solver node to retrieve the xmesh information set the property solname as in this command CHAPTER 4 WORKING WITH MODELS info mphxmeshinfo model soltag lt soltag gt where lt soltag gt is the tag of the solver used to extract the xmesh information To retrieve the xmesh information for a specific study step node specify it with the property studystepta
103. atio 20 dis2 meshi feature create dis2 Distribution dis2 selection set 1 3 dis2 set type predefined dis2 set method geometric dis2 set elemcount 20 dis2 set elemratio 20 mapi mesh1 feature create map1 Map map1 selection geom geomi 2 map1 selection set 2 mesh1 feature create frt1 FreeTri mesh1 run mphmesh model WORKING WITH MESHES 6l 62 CHAPTER 3 The final mesh is in Figure 3 7 Note the effect of the Distribution feature with which the distribution of vertex elements along geometry edges can be controlled Figure 3 7 Incrementally generated mesh right The left hand side plot in Figure 3 7 is obtained with this command mphgeom model geomi edgelabels on To replace the structured quad mesh by an unstructured quad mesh delete the Map feature and replace it by a FreeQuad feature mesh1 feature remove map1 meshi run dis1 fqi mesh1 feature create fqi FreeQuad fqi selection geom geom1 2 set 2 mesh1 run Analogous to working with the meshing sequence in the Model Builder in the COMSOL Desktop new features are always inserted after the current feature Thus to get the FreeQuad feature before the FreeTri feature the dis1 feature needs to be made the current feature by building it with the run method Alternatively parts of a mesh can be selectively removed by using the
104. ation edim defines the element dimension line surface volume or as an integer value v1 Vvn mphmean model e1 en edim also returns the units of the maximum in a 1xN cell array The function mphmean accepts the following property value pairs TABLE 6 14 PROPERTY VALUE PAIRS FOR THE MPHMEAN COMMAND PROPERTY PROPERTY VALUE DEFAULT DESCRIPTION Dataset String active Data set tag solution data set Intorder Positive integer 4 Integration order Matrix off on on Returns data as a matrix or as a cell Method auto auto Integration method integration summation Outersolnum Positive integer 1 Solution number for array parametric sweep Selection Integer vector all Selection list or named string all selection Solnum Integer vector all Solution for evaluation end all Squeeze on off on Squeeze singleton dimensions T Double array Time for evaluation The property Dataset controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on Solution Data Sets The mean of expressions e1 en is evaluated for one or several solutions Each solution generates an additional column in the returned matrix The property COMMAND REFERENCE mphmean Example See also Solnum and t control which solutions are used for the evaluation The Solnum property is available when the data set has multiple so
105. balmatrix model lt expr gt The output data M is a NxN double array where N is the number of port boundary condition set in the model SPECIFY THE EVALUATION DATA Set the solution data set for evaluation with the property dataset data mphevalglobalmatrix model lt expr gt dataset lt dsettag gt where lt dsettag gt is the tag of a solution data Evaluating a Maximum of Expression Use the function mphmax to evaluate the maximum of a given expression over an inner solution list To evaluate the maximum of the COMSOL expressions e1 en use the command mphmax as follows d1 dn mphmax model el en edim where edim isa string to define the element entity dimension volume surface or line edim can also be set as a positive integer value 3 2 or 1 respectively The output variables d1 dn are an NxP array where N is the number of inner solutions and P the number of outer solutions SPECIFY THE EVALUATION DATA The function mphmax supports the following properties to set the data of the evaluation to perform e dataset specify the solution data set to use in the evaluation data mphmax model lt expr gt edim dataset lt dsettag gt lt dsettag gt is the tag ofa solution data set The default value is the current solution data set of the model e selection specify the domain selection for evaluation EXTRACTING RESULTS 131 132 data mphmax mo
106. bles the model history To activate the model history enter the command model hist disable IMPROVING PERFORMANCE FOR LARGE MODELS 173 Creating a Custom GUI You can use the MATLAB guide functionality to create a GUI and connect the interface to a COMSOL model object Each operation at the GUI sets the value of a MATLAB variable or calls a MATLAB command As described in this guide you can call commands at the MATLAB prompt to set up a COMSOL model object or set MATLAB variables in the COMSOL model object The figure below illustrates a GUI made in MATLAB and linked to a COSMOL model object E heatgui elaks Geometry Radius 0 025 Position 4 gt Surface Temperature K 560 454 560 452 560 45 Geom plot Mesh 560 448 560 446 560 444 Mesh piot 560 442 r Physics Heat source 5 560 44 0 0 05 0 1 0 15 0 2 Solve The simplified GUI only allows the user to compute a heat transfer problem on a given geometry The user can only change the radius and the position of the bottom circle geometry The heat source applied to the bottom circle is also defined by the user The button executes the building operation of the geometry and mesh Another button executes the computation of the solution 174 CHAPTER 4 WORKING WITH MODELS COMSOL 3 5a Compatibility COMSOL makes an effort to be backward compatible you can load model
107. by mpheval as input Extracting Data at Arbitrary Points The function mphinterp evaluates at the MATLAB prompt the result at arbitrary points To evaluate an expression at specific point coordinates call the function mphinterp as in the command d1 dn mphinterp model el en coord lt coord gt where e1 en are the COMSOL expressions to evaluate lt coord gt is a NxM double array with N the space dimension of the evaluation domain and M is the number of evaluation points The output d1 dnisaPxM double array where P is the length of the inner solution Alternatively specify the evaluation coordinates using a selection data set data mphinterp model lt expr gt dataset lt dsettag gt where lt dsettag gt is a selection data set tag defined in the model for example Cut point Cut Plane Revolve and so forth SPECIFY THE EVALUATION DATA The function mphinterp supports the following properties to set the data of the evaluation to perform e dataset specify the solution data set to use in the evaluation data mphinterp model lt expr gt coord lt coord gt dataset lt dsettag gt lt dsettag gt is the tag ofa solution data set The default value is the current solution data set of the model e selection specify the domain selection for evaluation CHAPTER 4 WORKING WITH MODELS data mphinterp model lt expr gt coord lt coord gt selection
108. cemode vertexlabels vertexlabelscolor vertexmode Use mphgeom to display a specified geometry entity To set the geometry entity enter the entity property and set the geometry entity index in the selection property to mphgeom model lt geomtag gt entity entity selection lt idx gt where entity can be either point edge boundary or domain and lt idx gt is a positive integer array that contains the list of the geometry entity indices Working with Geometry Sequences This section shows how to create geometry sequences using the syntax outlined in The Geometry Sequence Syntax CREATING A ID GEOMETRY Q For more information about 1D geometry modeling see Creating a 1D See Also Geometry Model in the COMSOL Multiphysics User s Guide From the MATLAB command prompt create a 1D geometry model by adding a geometry sequence and then adding geometry features The last step is to run the sequence using the run method First create a model object model ModelUtil create Model Then continue with the commands geom1 model geom create geomi 1 il geom1 feature create i1 Interval i1 set intervals many 34 CHAPTER 3 BUILDING MODELS i1l set p 0 1 2 geom1 run This creates a geometry sequence with a 1D solid object consisting of vertices at x 0 1 and 2 and edges joining the vertices adjacent in the coordinate list Then enter p1 geom1 feature create
109. cific module in the documentation ip tree CHAPTER 2 GETTING STARTED Running COMSOL with MATLAB The command to run COMSOL with MATLAB automatically connects a COMSOL process with MATLAB You can also connect the process manually This section describes how to automatically and manually start COMSOL with MATLAB as well as how to change the MATLAB path in the COMSOL settings Note The System Requirements section of the COMSOL Installation and Operations Guide lists the versions of MATLAB supported by LiveLink for MATLAB In this section e Starting COMSOL with MATLAB on Windows Mac OSX Linux e Connecting the COMSOL Server and MATLAB Manually e Changing the MATLAB Version Starting COMSOL with MATLAB on Windows Mac OSX Linux To run a COMSOL model at the MATLAB prompt first start COMSOL with MATLAB e On Windows use the COMSOL with MATLAB shortcut icon that is created on the desktop after the automatic installation A link is also available in the Windows start menu under All Programs gt COMSOL 43a gt COMSOL 4 3a with MATLAB e On Mac OS X use the COMSOL with MATLAB application available in the application folder On Linux enter the command comsol server matlab at a terminal window See the COMSOL Multiphysics Installation and Operations Guide to a get a complete description on how to start COMSOL with MATLAB on See Also the different supported platforms RUNNING COMSOL WITH MATLAB 19 20
110. cify the solution data set to use in the evaluation data mphmean model lt expr gt edim dataset lt dsettag gt lt dsettag gt is the tag ofa solution data set The default value is the current solution data set of the model e selection specify the domain selection for evaluation data mphmean model lt expr gt edim selection lt seltag gt where lt seltag gt is the tag ofa selection node to use for the data evaluation lt seltag gt can also be a positive integer array that corresponds to the domain index list The default selection is all domains where the expression is defined If the evaluation point does not belong to the specified domain selection the output value is NaN e solnum specify the inner solution number for data evaluation Inner solutions are generated for the following analysis types time domain frequency domain eigenvalue or stationary with continuation parameters EXTRACTING RESULTS 133 134 data mphmean model lt expr gt edim solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index You can also set the property solnumto end to evaluate the expression for the last inner solution By default the evaluation is done using the last inner solution e outersolnum specify the outer solution number for data evaluation Outer solutions are generated with parametric sweeps data mphmean model lt expr gt edim outersolnum
111. curve model ModelUtil create Model gi model geom create g1 2 w 1 sqrt 2 c1 g1 feature create c1 BezierPolygon c1 set type open c1 set degree 2 c1 set p 0 5 1 1 0 5 0 5 0 ci set w 1 w 1 c2 gi feature create c2 BezierPolygon c2 set type open c2 set degree 2 c2 set p 1 1 0 5 0 0 5 0 5 c2 set w 1 w 1 c3 g1 feature create c3 BezierPolygon c3 set type open c3 set degree 1 c3 set p 0 5 0 5 0 5 0 5 c4 gi feature create c4 BezierPolygon c4 set type open c4 set degree 2 c4 set p 0 5 1 1 0 5 0 5 0 c4 set w 1 w 1 c5 gi feature create c5 BezierPolygon c5 set type open c5 set degree 2 c5 set p 1 1 0 5 0 0 5 0 5 c5 set w 1 w 1 c6 g1 feature create c6 BezierPolygon c6 set type open c6 set degree 1 c6 set p 0 5 0 5 0 5 0 5 The objects c1 c2 c3 c4 c5 and c6 are all curve2 objects The vector 1 w 1 specifies the weights for a rational B zier curve that is equivalent to a quarter circle arc The weights can be adjusted to create elliptical or circular arcs Convert the curve segments to a solid with the following conversion command BUILDING MODELS csol1 g1 feature create csol1 ConvertToSolid csol1 selection input set c1 c2 c3 c4 Then issue a final run command gi run mph
112. d to a study node this can be done with the command model sol lt soltag gt study lt studytag gt where lt studytag gt is the tag of the study you want to associate the solver sequence defined with the tag lt soltag gt A solver sequence also requires the definition of the following nodes e Study Step where you specify which study and study step to use when compiling the equations for and computing the current solver sequence e Dependent Variables this node handles settings for the computation of dependent variables such as initial value and scaling settings but also the dependent variables not solved for e Solver node where you specify the type of solver to use to compute the solution Add the nodes to the solver sequence with the command model sol lt soltag gt feature create lt ftag gt operation where lt soltag gt is the string defined when creating the solver sequence The string ftag is a string that is defined to refer to the node for example a study step operation can be one of the following StudyStep Variables or Stationary To specify a property value pair for a solver feature enter COMPUTING THE SOLUTION 99 100 model sol lt soltag gt feature lt ftag gt set property lt value gt where lt soltag gt is a string referring to the solver sequence configuration For a list of the operations available for the solver node see Features ol Producing and Manipulating S
113. del lt expr gt edim selection lt seltag gt where lt seltag gt is the tag of a selection node to use for the data evaluation lt seltag gt can also be a positive integer array that corresponds to the domain index list The default selection is all domains where the expression is defined If the evaluation point does not belong to the specified domain selection the output value is NaN solnum specify the inner solution number for data evaluation Inner solutions are generated for the following analysis type time domain frequency domain eigenvalue or stationary with continuation parameters data mphmax model lt expr gt edim solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index You can also set the property solnum to end to evaluate the expression for the last inner solution By default the evaluation is done using the last inner solution outersolnun specify the outer solution number for data evaluation Outer solutions are generated with parametric sweeps data mphmax model lt expr gt edim outersolnum lt outersolnum gt where lt outersolnum gt is a positive integer array corresponding to the outer solution index The default setting uses the first outer solution for the data evaluation To evaluate the expression data at a specific time use the property t data mphmax model lt expr gt edim t lt time gt where lt time gt is a doubl
114. dices provided with the Solnum property are used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated Solnum is used to select the solution number when a parametric eigenvalue or time dependent solver has been used Outersolnum is used to select the outer solution number when a parametric sweep has been used in the study step node If the Matrix property is set to of f the output will be cell arrays of length P containing cell arrays of length M Load micromixer mph from the Model Library model mphload micromixer mph Find the maximum x velocity u at the outlet boundary and get its unit flow unit mphmax model u surface selection 136 Load heat_transfer_axi mph from the Model Library model mphload heat_transient_axi mph Find the max normal heat flux along the external boundaries Q mphmax model ht ndflux line selection 2 3 4 mphmean mphmin 231 mphmean 232 CHAPTER 6 Purpose Syntax Description Perform mean of expressions v1 vn mphmean model e1 en edim v1 vn unit mphmean model e1 en edim v1 Vvn mphmean model e1 en edim evaluates the means of the string expressions e1 en and returns the result in N matrices v1 vn with M rows and P columns M is the number of inner solution and P the number of outer solution used for the evalu
115. ding Model Expressions Solutions starts a GUI to display the solution object available in the COMSOL model object Show Errors lists the error or warning nodes available in the model object see Handling Errors and Warnings NAVIGATING THE MODEL 163 e The Settings menu only contains the Advanced options Click it to select or deselect the advanced model object methods that are displayed in the Model Viewer tree e The Help menu THE SHORTCUT ICON Just under the menu bar are two shortcut buttons Plot and Help File Tools Settings Help aa These buttons are grayed if no method has been selected in the Model Tree section The Plot button displays the geometry the mesh or a plot group in a MATLAB figure The Help button displays the page of the COMSOL Java API Reference Guide of the corresponding method in your default web browser THE MODEL TREE SECTION m Model Tree Work Plane 1 amp COMSOL Model A i batch H coordSystem cpl H frame i func B geom geom1 is amp i Br difl fill model geom geom1 feature wp1 Copy _ The Model Tree section has the list of the nodes of the model object Use the scroll bar to the right to scroll down the list and click the icon to expand the model object feature nodes 164 CHAPTER 4 WORKING WITH MODELS When a feature node is selected its associated command is listed just beneath the model tree
116. e Load busbar mph from the Model Library model mphload busbar mph Extract xmesh information for the active Solver feature info mphxmeshinfo model Extract xmesh information from the Study Step node st1 261 mphxmeshinfo info mphxmeshinfo model solname sol1 studysteptag st1 See also mphgetu mphmatrix mpbhsolinfo 262 CHAPTER 6 COMMAND REFERENCE Index A access methods 243 adaptive solver 227 advancing front method 57 animations 10 ASCII file 111 ASCII format 110 B Boolean operations 39 boundary layer meshes 66 cC CAD formats 42 circle 36 Compose operation 36 COMSOL API 26 COMSOL Desktop 26 exchanging geometries with 41 COMSOL Multiphysics binary files 73 COMSOL Multiphysics text files 73 constructor name 81 converting meshes 72 copying boundary meshes 70 D data sets syntax for 108 Delaunay method 57 Difference operation 36 documentation finding 12 DXF files 42 E emailing COMSOL 13 equations global 86 modifying 85 evaluating data 109 exporting data for file 110 extruding meshes by sweeping 64 F file formats mphbin files 42 mphtxt files 42 fluid flow 66 free quad mesh 58 function inputs outputs 183 GDS format 42 geometries ID 34 2D 35 3D 39 exchanging with the COMSOL Desk top 41 parameterized 44 geometry sequences 32 getType methods 243 importing meshes 73 Internet resources Java 26 knowledge base COMSOL 14 mass mat
117. e csol1 ConvertToSolid wp2 geom feature csol1 selection input set b1 Revolve the triangle from the yz work plane revi geomi feature create revi1 Revolve rev1 selection input set wp2 revi1 setIndex pos 1 0 Add the difference operation that computes the final 3D geometry dif1 geom1 feature create dif1 Difference dif1 selection input set ext1 dif1 selection input2 set rev1 To run the sequence enter model geom geom1 run To view the geometry enter 40 CHAPTER 3 BUILDING MODELS mphgeom model Exchanging Geometries with the COMSOL Desktop EXCHANGING A GEOMETRY FROM THE COMSOL DESKTOP To transfer a geometry from the COMSOL Desktop to the LiveLink interface in MATLAB use one of these methods Export the Geometry from the COMSOL Desktop Export the geometry as a COMSOL Multiphysics binary mphbin file from the COMSOL Desktop Right click the Geometry node and select Export to File Then create a geometry import feature from MATLAB model ModelUtil create Model geom1 model geom create geom1 3 imp1 geom1 feature create imp1 Import imp1 set filename geometryfile mphbin imp1 importData geom1 run Save the Geometry Save the model containing the geometry sequence from the COMSOL Desktop Create a model object from MATLAB and load the file into it Export the Model to the COMSOL Server Export the
118. e Model Library mphnavigator GUI for viewing the COMSOL model object mphsearch GUI for searching expressions in the COMSOL model object mphshowerrors Show messages in error and warning nodes in the COMSOL model object COMMANDS GROUPED BY FUNCTION I9I colortable 192 Purpose Syntax Description Return a MATLAB colormap for a COMSOL color table map colortable name map colortable name returns the color table of 1024 colors for name where name can be one of the following strings Cyclic A color table that varies the hue component of the hue saturation value color model keeping the saturation and value constant equal to 1 The colors begin with red pass through yellow green cyan blue magenta and return to red This table is particularly useful for displaying periodic functions and has a sharp color gradient Disco This color table spans from red through magenta and cyan to blue Discolight Similar to Disco but uses lighter colors Grayscale A color table that uses no color only the gray scale varying linearly from black to white Grayprint Varies linearly from dark gray 0 95 0 95 0 95 to light gray 0 05 0 05 0 05 This color table overcomes two disadvantages that the GrayScale color table has when used for printouts on paper namely that it gives the impression of being dominated by dark colors and that white cannot be distinguished from the background Rainbow T
119. e array The default value corresponds to all the stored time steps OUTPUT FORMAT The function mphmax also supports other output formats To extract the unit of the evaluated expression define an extra output variable data unit mphmax model lt expr gt edim with unit is a 1xN cell array where N is the number of expressions to evaluate By default mphmax returns the results as a squeezed singleton To get the full singleton set the squeeze property to off data mphmax model lt expr gt edim squeeze off CHAPTER 4 WORKING WITH MODELS Set the property matrix to off to return the data as a cell array instead of a double array data mphmax model lt expr gt edim matrix off Evaluating an Expression Average Use the function mphmean to evaluate the average of a given expression over inner solution lists To evaluate the mean of the COMSOL expressions e1 en use the command mphmean as follows d1 dn mphmean model ece1 en edim where edim isa string to define the element entity dimension volume surface or line edim can also be set as a positive integer value 3 2 or 1 respectively The output variables d1 dn are an NxP array where N is the number of inner solutions and P the number of outer solutions SPECIFY THE EVALUATION DATA The function mphmean supports the following properties to set the data of the evaluation to perform e dataset spe
120. e methods active or remove respectively The command model physics lt phystag gt feature lt ftag gt active false disables the feature lt ftag gt To activate the feature node you can set the active method to true model physics lt phystag gt feature lt ftag gt active true To remove a feature from the model use the method remove model physics lt phystag gt feature remove lt ftag gt EXAMPLE IMPLEMENT AND SOLVE A HEAT TRANSFER PROBLEM This example details how to add a physics interface and set the boundary conditions in the model object Start to create a model object including a 3D geometry The geometry consists in a block with default settings Enter the following commands at the MATLAB prompt model ModelUtil create Model geom1 model geom create geom1 3 geom1 feature create blk1 Block geom1 run Add a Heat Transfer in Solids physics interface to the model phys model physics create ht HeatTransfer geom1 The tag of the interface is ht The physics interface constructor is HeatTransfer The physics is defined on geometry geom1 The physics interface automatically creates a number of default features To examine these enter gt gt model physics ht BUILDING MODELS ans Type Heat Transfer in Solids Tag ht Identifier ht Operation HeatTransfer Child nodes solidi ins1 cibi initi os1 The physics method has the following child nodes
121. ear these coordinates using a tolerance radius The list of the entities that are adjacent to such vertices is returned Coord is a NxM array where N correspond of the number of point to use and M the space dimension of the geometry Entity can be one of point edge boundary or domain following the entity space dimension defined below e domain maximum geometry space dimension e boundary maximum geometry space dimension 1 e edges l only for 3D geometry The function mphpselectcoords accepts the following property value pairs TABLE 6 21 PROPERTY VALUE PAIRS FOR THE MPHSELECTCOORDS COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Adjnumber Scalar none Adjacent entity number Radius Scalar auto Search radius Include all any all Include all or any vertices When a model uses form an assembly more than one vertex may have the same coordinate if the coordinate is shared by separate geometric objects In that case one can use the adjnumber property in order to identify the domain that the vertices should be adjacent to The radius property is used to specify the radius of the sphere circle that the search should be within A small positive radius based on the geometry size is used by default in order to compensate for rounding errors Ifthe include property is al1 then all vertices must belong to the entity in to be considered a match If the Include property is any then an entity is considered a
122. ection Exchanging Models Between MATLAB and the COMSOL Desktop An alternative approach is to call the function mphnavigator that displays the model object information in a MATLAB graphical user interface To run the function type at the MATLAB prompt enter the command mphnavigator Prior to calling mphnavigator make sure that the MATLAB object El linked the COMSOL model object has the same name No other name is Note currently supported CHAPTER 4 WORKING WITH MODELS This command pops up a MATLAB GUL as in the figure below Ed rphnevigatce Model Object Navigator COMSOL Multiphysics gt o ES Fae Tools Settings Help Model Viewer Properties 1 3 4 modelNode om Copy Copy Table Copy Methods 1 2 1 3 4 Copy 0 If a new model object is created with the MATLAB object name mode1 imponan restart mphnavigator in order to have the updated model information mportan THE MENU BAR ITEMS 7 2 mphnavigator Model Object Navigator COMSOL Multiphysics File Tools Settings Help The mphnavigator GUI menu bar has the following menu e The File menu where the current model object can be saved in the MPH format a new model object can be opened and the mphnavigator window can be closed e The Tools menu lists the navigation tools available for the model object Search is a shortcut to the command mphsearch that starts a GUI to search expressions or tags in the model object see also Fin
123. el Settings LiveLink for MATLAB allows you to define the model properties with MATLAB variables or a MATLAB M function In this section e The Set and SetIndex Methods e Using a MATLAB Function to Define Model Properties The Set and SetIndex Methods You can use MATLAB variables to set properties of a COMSOL model Use the set or setIndex methods to pass the variable value from MATLAB to the COMSOL model THE SET METHODS Use the set method to assign parameter and or property values All assignments return the parameter object which means that assignment methods can be appended to each other The basic method for assignment is something Set name lt value gt The name argument is a string with the name of the parameter property The lt value gt argument can for example be a MATLAB integer or double array variable When using a MATLAB variable make sure that the value corresponds to the model unit system COMSOL can also take care of the unit conversation automatically in this case convert the MATLAB integer double variable to a string variable and use the set method as something Set property num2str lt value gt unit where is the unit you want to set the value property CHAPTER 4 WORKING WITH MODELS THE SETINDEX METHODS Use the set Index methods to assign values to specific indices 0 based in an array or matrix property All assignment methods return the parameter object which means that
124. el object model The contour of the image is defined by the value level imagedata must be a 2D matrix The function mphimage2geom accepts the following property value pairs TABLE 6 7 PROPERTY VALUE PAIRS FOR THE MPHIMAGE2GEOM COMMAND PROPERTY PROPERTY VALUE DEFAULT DESCRIPTION Rtol Value 1e 3 Relative tolerance for interpolation curves Type Solid closed solid Type of geometry object open Curvetype Auto polygon auto Type of curve to create the geometry object Scale Value 1 Scale factor from pixels to geometry scale Mindist Value 1 Minimum distance between coordinates in curves in pixels Compose on off on Create compose nodes for overlapping solids Rectangle on off off Insert rectangle in the geometry The default curve types creates a geometry with the best suited geometrical primitives For interior curves this is Interpolation Curves and for curves that are touching the perimeter of the image Polygons is used Create the geometry following the contour level 50 ofan image data array provided by the function peaks p peaks 7 5 figure 1 c h contourf p clabel c h colorbar model mphimage2geom p 50 figure 2 215 mphimage2geom mphgeom model 216 CHAPTER 6 COMMAND REFERENCE mphinputmatrix Purpose Syntax Description Add linear matrix system to a model mphinputmatrix model str soltag soltypetag mphinputmatrix model str soltag soltypet
125. electbox mphselectcoords 206 CHAPTER 6 COMMAND REFERENCE mphgetcoords Purpose Syntax Description Example See also Return point coordinates of geometry entities O ll mphgetcoords model geomtag entitytype entitynumber c mphgetcoords model geomtag entitytype entitynumber returns the coordinates of the points that belong to the entity object with the type entitytype and the index entitynumber The entitytype property can be one of point edge boundary or domain following the entity space dimension defined below e domain maximum geometry space dimension e boundary maximum geometry space dimension 1 e edge 1 only for 3D geometry point 0 Load busbar mph from the Model Library model mphload busbar mph Return the coordinates of points that belong to domain 1 c mphgetcoords model geom1 domain 1 Return the coordinates of points that belong to boundary 5 c mphgeomcoords model geom1 boundary 5 Return the coordinates of point number 10 c mphgeomcoords model geom1 point 10 mphgetadj mphselectbox mphselectcoords 207 mphgetexpressions 208 Purpose Syntax Description Example See also Get the model variables and model parameters expressions expr mphgetexpressions modelnode expr mphgetexpressions modelnode returns expressions from the node modelnode as a cell array expr contains the list of the var
126. election in dimension Edim is used If the number of rows in coord is less than the space dimension then these coordinates are parameter values on a geometry face or edge In that case the domain number for that face or edge must be specified with the property Selection The expressions that are evaluated can be expressions involving variables in particular physics interface variables The matrices v1 vn are of the size k by size coord 2 where k is the number of solutions for which the evaluation is carried out see below The value of expression ei for solution number j in evaluation point coord m is vi j m The vector pe contains the indices m for the evaluation points code m that are outside the mesh or if a domain is specified are outside that domain 223 mphinterp 224 CHAPTER 6 The property Data controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on Solution Data Sets The active solution data set is used by default The property Edim decides which elements to evaluate on Evaluation takes place only on elements with space dimension Edim If not specified Edim equal to the space dimension of the geometry is used The setting is specified as one of the following strings point edge boundary or domain In previous versions it was only possible to specify Edim as a number For exa
127. elocity u at the outlet boundary and get its unit flow unit mphmin model u surface selection 136 Load heat_transfer_axi mph from the Model Library model mphload heat_transient_axi mph Find the minimum normal heat flux along the external boundaries Q mphmin model ht ndflux line selection 2 3 4 mphmax mphmean CHAPTER 6 COMMAND REFERENCE mphmodel Purpose Syntax Description Example See also Return tags for the nodes and subnodes in the COMSOL model object mphmodel model str mphmodel model struct mphmodel mode1 returns the tags for the nodes and subnodes of the object mode1 str mphmodel model struct returns the tags for the nodes and subnodes of the object model as a MATLAB structure str The function mphmode1 can be used when navigating the model object and learning about its structure The mphmodel function is mainly designed for usage when working on the command line and one needs to learn what nodes are placed under a particular node Load transport_and_adsorption mph from the Model Library model mphload transport_and_adsorption See what nodes are available under the model object mphmodel model See what nodes are available under the geometry node mphmodel model geom Get the model information as a structure res mphmodel model struct mphnavigator mphsearch 239 mphmodellibrary Purpose Graphical User Interface for
128. er sweep Selection Integer All Set selection tag or entity number vector domains string all Smooth Internal internal Smoothing setting none everywhere Solnum Integer all Solutions for evaluation vector all end Squeeze on off on Squeeze singleton dimension t Double Times for evaluation array The property Dataset controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on Solution Data Sets 201 mphevalpoint 202 Example The Dataseries property is used to control any filtering of the data series The supported operations are average mean integral int maximum max minimum min root mean square rms standard deviation std and variance var Set the property Matrix to off to get the results in a cell array format In case the property Datseries is either min or max you can specify the how the value are treated using the property Minmaxobj Use either the real data or the absolute data The property Solnum is used to select the solution to plot when a parametric eigenvalue or time dependent solver has been used to solve the problem The expressions e1 en are evaluated for one or several solutions Each solution generates an additional row in the data fields of the post data output structure The property Solnum and t control which solutions are used for the evaluations The S
129. eshes using the BndLayer feature A boundary layer mesh is a mesh with dense element distribution in the normal direction along specific boundaries This type of mesh is typically used for fluid flow problems to resolve the thin boundary layers along the no slip boundaries In 2D a layered quadrilateral mesh is used along the specified no slip BUILDING MODELS boundaries In 3D a layered prism mesh or hexahedral mesh is used depending on whether the corresponding boundary layer boundaries contain a triangular or a quadrilateral mesh If starting with an empty mesh the boundary layer mesh uses free meshing to create the initial mesh before inserting boundary layers into the mesh This generates a mesh with triangular and quadrilateral elements in 2D and tetrahedral and prism elements in 3D The following example illustrates this in 2D model ModelUtil create Model1 geom1 model geom create geomi 2 ri geom1 feature create r1 Rectangle r1 set size 10 5 c1 geom1 feature create ci Circle c1 set pos 3 5 2 5 difi geom1 feature create difi Difference difi1 selection input set ri dif1 selection input2 set c1 geom1 runAll mesh1 model mesh create mesh1 geom1 bli meshi feature create b11 BndLayer b11 feature create blp1 BndLayerProp b11 feature blp1 selection set 2 3 5 6 7 8 mesh1 run mphmesh model WORKING WITH MES
130. etry s tag an identifier of your choice When the string is predefined by COMSOL no bracket is used and this indicates that this is a finite set such as a feature name KEY TO THE GRAPHICS Throughout the documentation additional icons are used to help navigate the information These categories are used to draw your attention to the information based on the level of importance although it is always recommended that you read these text boxes ICON NAME DESCRIPTION A Caution Important Note A Caution icon is used to indicate that the user should proceed carefully and consider the next steps It might mean that an action is required or if the instructions are not followed that there will be problems with the model solution An Important icon is used to indicate that the information provided is key to the model building design or solution The information is of higher importance than a note or tip and the user should endeavor to follow the instructions A Note icon is used to indicate that the information may be of use to the user It is recommended that the user read the text A Tip icon is used to provide information reminders shortcuts suggestions of how to improve model design and other information that may or may not be useful to the user HELP AND DOCUMENTATION 15 16 CHAPTER I ICON NAME DESCRIPTION Q See Also W Model Space Dimension The See Also icon
131. eturn geometric entity indices adjacent to each other mphgetcoords Return point coordinates of geometry entities mphgetu Return solution vectors mphinputmatrix Add a linear matrix system to a model mphmatrix Get model matrices mphselectbox Select a geometric entity using a rubberband box COMMAND REFERENCE FUNCTION PURPOSE mphselectcoords mphsolinfo mphstate mphxmeshinfo Select a geometric entity using point coordinates Get information about a solution object Get state space matrices for dynamic systems Extract information about the extended mesh Postprocessing Functions FUNCTION PURPOSE mpheval Evaluate expressions on node points mphevalglobalmatrix Evaluate global matrix variables mphevalpoint Evaluate expressions at geometry vertices mphglobal Evaluate global quantities mphinputmatrix Perform integration of expressions mphinterp Evaluate expressions in arbitrary points or data sets mphmax Perform maximum of expressions mphmean Perform mean of expressions mphmin Perform minimum of expressions mphplot Render a plot group in a figure window Model information and navigation FUNCTION PURPOSE mphgetproperties Get properties from a model node mphgetexpressions Get the model variables and parameters mphgetselection Get information about a selection node mphmodel Return tags for the nodes and subnodes in the COMSOL model object mphmodellibrary GUI for viewing th
132. f the evaluation to perform e dataset specify the solution data set to use in the evaluation data mphglobal model lt expr gt dataset lt dsettag gt lt dsettag gt is the tag ofa solution data set The default value is the current solution data set of the model e solnum specify the inner solution number for data evaluation Inner solutions are generated for the following analysis types time domain frequency domain eigenvalue or stationary with continuation parameters data mphglobal model lt expr gt solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index You can also set the property solnum to end to evaluate the expression for the last inner solution By default the evaluation is done using the last inner solution EXTRACTING RESULTS 129 130 e outersolnum specify the outer solution number for data evaluation Outer solutions are generated with parametric sweep data mphglobal model lt expr gt outersolnum lt outersolnum gt 5 where lt outersolnum gt is a positive integer corresponding to the outer solution index The default settings uses the first outer solution for the data evaluation e To evaluate the expression data at a specific time use the property t data mphglobal model lt expr gt t lt time gt where lt time gt is a double array The default value corresponds to all the stored time steps e phase
133. fault Set the property to none to evaluate the data on elements independently set to everywhere to apply the smoothing to the entire geometry and set to internal to smooth the quantity inside the geometry but no smoothing takes place across borders between domains with different settings The output with the same data and same coordinates are automatically merged which means that the output size may differ depending on the smoothing method e recover specify the accurate derivative recovery pd mpheval model lt expr gt recover recover where recover is either ppr pprint or off default Set the property to ppr to perform recovery inside domains or set to pprint to perform recovery inside domains Because the accurate derivative processing takes time the property is disabled by default OTHER EVALUATION PROPERTIES To not use complex value functions with real inputs use the property complexfun pd mpheval model lt expr gt complexfun off The default value uses complex valued functions with real inputs Use the property matherr to return an error for undefined operations or expressions EXTRACTING RESULTS 12I 122 pd mpheval model lt expr gt matherr on DISPLAY THE EXPRESSION IN FIGURES You can display an expression evaluated with mpheval in an external figure with the function mphplot see Displaying The Results The function mphplot only supports a MATLAB structure provided
134. fied MATLAB version may not start when calling external MATLAB function from the COMSOL model RUNNING COMSOL WITH MATLAB 2l 5 Click OK W Preferences a General LiveLink for MATLAB ae MATLAB installation folder C Program Files MATLAB R2012a Browse Expand sections Model Builder _ Register MATLAB As COM Server _ Clust uti Gemme i LiveLink for Pro ENGINEER Graphics Pro ENGINEER installation folder lt Results Builder Tools Temporary files LiveLink for Creo Parametric Memory and processors Creo Parametric common files folder a ess Use LiveLink for Creo Parametric commis Ca 6 To update the preferences file close the COMSOL Desktop 22 CHAPTER 2 GETTING STARTED Calling a MATLAB Function from the COMSOL Desktop Use LiveLink for MATLAB to call MATLAB functions from within the model when working in the COMSOL Desktop The procedure is slightly different than implementing a model using a script as you do not need to run COMSOL with MATLAB Start COMSOL as a standalone application The external MATLAB function needs to be defined in the COMSOL model so that a MATLAB process can automatically start when the function needs to be evaluated The result of the function evaluation in MATLAB is then sent back to the COMSOL environment Calling MATLAB Functions See Also CALLING A MATLAB FUNCTION FROM THE COMSOL
135. formation about the geometry in a model see Geometry Object Information in the COMSOL Java API Reference Note Guide CHAPTER 3 BUILDING MODELS First create a simple 3D geometry model ModelUtil create Model geom1 model geom create geom1 3 geom1 feature create blk1 Block geom1 feature create con1 Cone geom1 run To visualize the geometry in a MATLAB figure window enter mphgeom model The model object contains general geometry information methods For example to determine the space dimension of the geometry enter geom1 getSDim There are also methods to determine the number of geometrical entities For example to inquire about the number of domains and the number of boundaries geom1 getNDomains geom1 getNBoundaries Another group of geometry information methods concern adjacency properties of the geometric entities For example the number of up and down domain information on each boundary geomi getUpDown There are also methods for evaluating properties such as coordinate values and curvatures on faces and edges For example to evaluate coordinates on face 1 for the face parameters 2 0 005 enter WORKING WITH GEOMETRY 43 44 CHAPTER 3 geom1 faceX 1 2 0 005 To get the parameters of a given face use the method faceParamRange N where N is the face number For example geom1 faceParamRange 1 returns the parameters for face 1 To get the pa
136. g info mphxmeshinfo model studysteptag lt studysteptag gt where lt studysteptag gt is the tag of either a compiled equation node or a variable node In case several mesh cases have been used by a specific solver for example with an automatic remeshing procedure you can specify which mesh case to use to get the discretization information info mphxmeshinfo model meshcase lt meshcase gt where lt meshcase gt is the mesh case number or the tag of the mesh case RETRIEVING XMESH INFORMATION 161 162 Navigating the Model The model object contains all the finite element model settings To retrieve the model information you can navigate in the model object using a graphical user interface or directly at the MATLAB prompt Learn how to get the list of predefined expressions available for a given model and how to extract the value of these expressions and also the properties of the method used in the model In this section e Navigating the Model Object Using a GUI e Navigating The Model Object At The Command Line e Finding Model Expressions e Getting Feature Model Properties e Getting Model Expressions e Getting Selection Information Navigating the Model Object Using a GUI The usual approach to navigate through the model object in a graphical user interface is to load the model object at the COMSOL Desktop Then transfer the model object from the COMSOL server to the COMSOL Desktop as in the s
137. geom model g1 O6F 1 08 06 04 02 0 02 04 06 08 1 CREATING A 3D GEOMETRY USING SOLID MODELING c5 c6 For more information about 3D geometry modeling see Creating a 3D See Also Geometry Model in the COMSOL Multiphysics User s Guide This section shows how to create 3D solids using workplanes and Boolean operations Create a 3D geometry with an xy work plane at z 0 model ModelUtil create Model geom1 model geom create geom1 3 wp1 geom1 feature create wp1 WorkPlane wp1 set planetype quick wp1 set quickplane xy Add a rectangle to the work plane then add fillet to its corners ri wo1 geom feature create r1 Rectangle r1 set size 1 2 geom1 run WORKING WITH GEOMETRY 39 fili wp1 geom feature create fil1 Fillet fil1 selection point set ri 1 2 3 4 fili set radius 0 125 geom1 runCurrent exti geom1 feature create exti Extrude ext1 set distance 0 1 Add another yz work plane at x 0 5 wp2 geom1 feature create wp2 WorkPlane wp2 set planetype quick wp2 set quickplane yz wp2 set quickx 0 5 b1 wp2 geom feature create b1 BezierPolygon b1 set type open b1 set degree 1 1 1 1 b1 set p 0 75 1 1 0 8 0 75 5 0 1 0 1 0 05 0 05 0 1 b1 set w 1 1 1 1 1 1 1 1 5 wp2 geom feature creat
138. gt curvetype curvetype where curvetype can be set to polygon to use a polygon curve The default curve type creates a geometry with the best suited geometrical primitives For interior curves it uses interpolation curves while for curves that are touching the perimeter of the image a polygon curve is used To scale the geometry use the scale property where scale is a double value model mphimage2geom lt imagedata gt lt level gt scale scale Set the minimum distance between coordinates in curve with the mindist property where mindist is a double value model mphimage2geom lt imagedata gt lt level gt mindist mindist Set the minimum area for interior curves where minarea is a double value model mphimage2geom lt imagedata gt lt level gt minarea minarea In case of overlapping solids the function mphimage2geom automatically creates a Compose node in the model object If you do not want this geometry feature set the property compose to off model mphimage2geom lt imagedata gt lt level gt compose off To create a rectangle domain surrounding the object generated use the property rectangle model mphimage2geom lt imagedata gt lt level gt rectangle on Example Convert Image Data to Geometry This example illustrates how to create geometry based on gray scale image data First generate the image data in MATLAB and display the contour in a figure Then create
139. gt feature lt studysteptag gt set plotgroup lt ptag gt Only one plot group can be plotted during a computation Use the probe feature instead if you need to monitor several variables To activate Plot While Solving for a probe plot enter the command model study lt studytag gt feature lt studysteptag gt set probesel seltype where seltype is the type of probe selection that can be none all or manual BUILDING MODELS In case the probe selection is set to manual you have to specify the list of the probe variable to display This is done with the command model study lt studytag gt feature lt studysteptag gt set probes lt list gt where lt list gt is the a cell array containing the list of the probe to use COMPUTING THE SOLUTION 103 104 Analyzing the Results This section describes how to do results analysis and visualization e The Plot Group Syntax e Displaying The Results e The Data Set Syntax e The Numerical Node Syntax e Exporting Data e Results Evaluation and Visualization in the COMSOL Multiphysics a User s Guide See Also Results in the COMSOL Java API Reference Guide i The links to features described outside of this user guide do not work in the PDF only from within the online help Important CHAPTER 3 The Plot Group Syntax Result plots always appear in plot groups which you add to the model by the create method mode
140. hat come with the product In this chapter e Summary of Commands e Commands Grouped by Function 187 Summary of Commands colortable mphcd mphdoc mpheval mphevalglobalmatrix mphevalpoint mphgeom mphgetadj mphgetcoords mphgetexpressions mphgetproperties mphgetselection mphgetu mphglobal mphimage2geom mphinputmatrix mphinterp mphload mphmatrix mphmax mphmean mphmesh mphmeshstats mphmin mphmodel mphmodellibrary mphnavigator mphplot mphsave mphsearch mphselectbox mphselectcoords mphshowerrors mphsolinfo mphstart 188 CHAPTER 6 COMMAND REFERENCE mphstate mphversion mphviewselection mphxmeshinfo SUMMARY OF COMMANDS 189 Commands Grouped by Function Interface Functions FUNCTION PURPOSE mphcd Change the directory to the directory of the model mphdoc Return HTML help of a specified function mphload Load a COMSOL model MPH file mphsave Save a COMSOL model mphstart Connect MATLAB to a COMSOL server mphversion Return the version number of COMSOL Multiphysics Geometry Functions FUNCTION PURPOSE mphgeom Plot a geometry in a MATLAB figure mphimage2geom Convert image data to geometry mphviewselection Display a geometric entity selection in a MATLAB figure Mesh Functions FUNCTION PURPOSE mphmesh Plot a mesh in a MATLAB figure mphmeshstats Return mesh statistics and mesh data information Utility Functions FUNCTION PURPOSE mphgetadj R
141. hcd model changes the current directory in MATLAB to the directory where the model was last saved See aalso mphload mphsave 194 CHAPTER 6 COMMAND REFERENCE mphdoc Purpose Syntax Description Example Return HTML help of a specified function mphdoc argi mphdoc argi arg2 mphdoc arg1 returns the HTML documentation associated to the function arg1 mphdoc argi arg2 returns the HTML documentation associated to the feature arg2 of the method arg1 mphdoc arg1 web returns the HTML documentation in the default web browser Create a model object model ModelUtil creat Model Get the documentation for the mesh node mphdoc model mesh Get the documentation of the rectangle geometry feature mphdoc model geom Rectangle Display the documentation in the default web browser mphdoc model sol web 195 mpheval Purpose Evaluate expressions on node points Syntax pd mpheval model e1 en Description pd mpheval model e1 en returns the post data pd for the expressions e1 eNn The output value pd is a structure with fields expr p t ve unit and fields for data values e The field expr contains the expression name evaluated e For each expression e1 ena field with the name d1 dn is added with the numerical values The columns in the data value fields correspond to node point coordinates in columns in p The data contains only the real part of complex valued e
142. he color ordering in this table corresponds to the wavelengths of the visible part of the electromagnetic spectrum beginning at the small wavelength end with dark blue the colors range through shades of blue cyan green yellow and red Rainbowlight Similar to Rainbow this color table uses lighter colors Thermal Ranges from black through red and yellow to white which corresponds to the colors iron takes as it heats up Thermalequidistant Similar to Thermal but uses equal distances from black to red yellow and white which means that the black and red regions become larger Traffic Spans from green through yellow to red Trafficlight Similar to Traffic but uses lighter colors Wave Ranges linearly from blue to light gray and then linearly from white to red When the range of the visualized quantity is symmetric around zero the color red CHAPTER 6 COMMAND REFERENCE colortable or blue indicates whether the value is positive or negative and the saturation indicates the magnitude Wavelight Similar to Wave and ranges linearly from a lighter blue to white instead of light gray and then linearly from white to a lighter red Calling colortable is equivalent to calling the corresponding colormap function directly Example Create a rainbow color map map colortable Rainbow map rainbow 193 mphcd Purpose Change directory to the directory of the model Syntax mphcd model Description mp
143. he function mphgetadj to select geometric entities using an adjacent domain To get a list of entities of type ent itytype adjacent to the entity with the index lt adjnumber gt of type adjtype enter idx mphselectbox model lt geomtag gt entitytype adjtype lt adjnumber gt where lt geomtag gt is the tag of geometry where the selection applies The string variables entitytype and adjtype can be one of point edge boundary or domain The list returned by the function can be used to specify the selection for a model feature or to create an explicit selection as described in Setting an Explicit Selection Displaying Selections Use the function mphviewselection to display the selected geometric entities in a MATLAB figure You can either specify the geometry entity index and its entity type or specify the tag of a selection node available in the model CREATING SELECTIONS 95 To display the entity of type entitytype with the index lt idx gt enter mphviewselection model lt geomtag gt lt idx gt entity entitytype where lt geomtag gt is the geometry node tag and lt idx gt is a positive integer array that contains the entity indices The string entitytype can be one of point edge boundary or domain If the model contains a selection node with the tag lt seltag gt it can be displayed with the command mphviewselection model lt geomtag gt lt seltag gt If the
144. he mesh If several mesh cases are available in the model object specify the mesh tag stats mphmeshstats model lt meshtag gt Getting and Setting Mesh Data The function mphmeshstats also returns the mesh data such as element coordinates Use the function with two output variable to get the mesh data Enter meshstats meshdata mphmeshstats model where meshdata is a MATLAB structure with the following fields e vertex which contains the mesh vertex coordinates e elem which contains the element data information e elementity which contains the element entity information for each element type EXAMPLE EXTRACT AND CREATE MESH INFORMATION You can manually create a mesh based on a grid generated in MATLAB However before inserting this mesh into the model a default coarse mesh is generated to get the mesh information This information enables you to understand the requested mesh structure to use with the createMesh method Then a complete mesh can be constructed and stored in the meshing sequence Ifthe geometry is not empty the new mesh is checked to ensure that it matches the geometry In summary to create an arbitrary mesh an empty geometry sequence and a corresponding empty meshing sequence need to be created and then the mesh is constructed on the empty meshing sequence Start by creating a 2D model containing a square and mesh it with triangles model ModelUtil create Model model modelNode create mod
145. hes in the COMSOL Multiphysics User s Guide Important a e Mesh in the COMSOL Java API Reference Guide 0 The links to features described outside of this user guide do not work in the PDF only from within the online help CHAPTER 3 The Meshing Sequence Syntax Create a meshing sequence by using the syntax model mesh create lt meshtag gt lt geomtag gt where lt meshtag gt is a string that you use to refer to the sequence The tag geomtag specifies the geometry to use for this mesh node To add an operation to a sequence use the syntax model mesh lt meshtag gt feature create lt ftag gt operation BUILDING MODELS where the string lt ftag gt is a string that you use to refer to the operation Q See About Mesh Commands in the COMSOL Java API Reference See Also Guide To set a property to a value in a operation enter model mesh lt meshtag gt feature lt ftag gt set property lt value gt To build the mesh sequence enter model mesh lt meshtag gt run Or to run the mesh node up to a specified feature node lt ftag gt enter model mesh lt meshtag gt run ftag Q For more details on available operations and properties in the sequence See Also see Mesh in the COMSOL Java API Reference Guide Displaying the Mesh To display the mesh in a MATLAB figure use the function mphmesh Make sure that the mesh is built before calling this command mphmesh
146. iable names the variable expressions and the variable descriptions Note that not all nodes have expressions defined Load example model busbar mph from the Model Library model mphload stresses_in_pulley mph Get the expressions defined in the parameters node expr mphgetexpressions model param mphnavigator mphmodel CHAPTER 6 COMMAND REFERENCE mphgetproperties Purpose Syntax Description Example See also Get the properties from a model node mphproperties modelnode mphproperties modelnode returns properties that are defined for the node modelnode Load busbar mph from the Model Library model mphload busbar Get the properties of the node model result pg1 prop mphgetproperties model result pgi mphnavigator 209 mphgetselection Purpose Syntax Description Example See also Get information about a selection node info mphgetselection selnode info mphgetselection selnode returns the selection data of the selection node selnode The output info isa MATLAB structure defined with the following fields e dimension the space dimension of the geometry entity selected geom the geometry tag e entities the indexes of the selected entities e isGlobal a Boolean expression that indicates if the selection is global Load busbar mph from the Model Library model mphload busbar mph Get the information of the selection node model
147. iable t can be used in the expressions ei The value of t is the interpolation time when the property t is provided and the time for the solution when Solnum is used Similarly Lambda and the parameter are available as eigenvalues for eigenvalue problems and as parameter values for parametric problems respectively Load micromixer mph from the Model Library model mphload micromixer mph Evaluate the pressure p at all node points dat mpheval model p Evaluate the concentration c at the outlet boundary dat mpheval model c edim boundary selection 136 Evaluate the pressure on all geometric vertices CHAPTER 6 COMMAND REFERENCE mpheval dat mpheval model p edim point Evaluate the pressure on vertex number 1 and return only the pressure value dat mpheval model p edim point selection 1 dataonly on See also mphevalpoint mphglobal mphinputmatrix mphinterp 199 mphevalglobalmatrix Purpose Syntax Description Example See also Evaluate global matrix variables M mphevalglobalmatrix model expr M mphevalglobalmatrix model expr evaluates the global matrix of the variable expr and returns the full matrix M The function mphevalglobalmatrix accepts the following property value pairs TABLE 6 2 PROPERTY VALUE PAIRS FOR THE MPHEVAL COMMAND PROPERTY PROPERTY DEFAULT DESCRIPTION VALUE Dataset String Data set tag Note S par
148. iffusivity Navigate the model object that is accessible with the variable ef f_diff mphnavigator eff_diff See also mphgetexpressions mphgetproperties mphgetselection mphmodel mphsearch 242 CHAPTER 6 COMMAND REFERENCE mphplot Purpose Syntax Description Example Render a plot group in a figure window mphplot model pgtag pd mphplot model pgtag mphplot pd mphplot model pgtag renders the plot group tagged pgtag from the model object model in a figure window in MATLAB pd mphplot model pgtag also returns the plot data used in the MATLAB figure in a cell array pd mphplot pd makes a plot using the post data structure pd that is generated using the function mpheval Plots involving points lines and surfaces are supported The function mphplot accepts the following property value pairs TABLE 6 19 PROPERTY VALUE PAIRS FOR THE MPHPLOT COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Colortable String Rainbow Color table used for plotting post data structure Index Positive 1 Index of variable to use plotting integer post data structure Rangenum Positive none Color range bar or legend to Integer display Server on off off Plot on server Parent Double Set the parent axes Note The plot on server option requires that you start COMSOL with MATLAB in graphics mode Only one color range bar and one legend bar is supported in a MATLAB figure When
149. igure mphgeom model mphgeom model geomtag mphgeom model plots the model geometry in a MATLAB figure mphgeom model geomtag in a MATLAB figure plots the model geometry with the tag geomtag The function mphgeom accepts the following property value pairs TABLE 6 4 PROPERTY VALUE PAIRS FOR THE MPHGEOM COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Parent Double Parent axes Selection Positive Selection integer array Entity point Geometric entity to edge select boundary domain Build on off on Build the geometry current before plotting string Edgecolor Char k Edge color Edgelabels on off off Show edge labels Edgelabelscolor Char k Color for edge labels Edgemode on off on Show edges Facealpha Double 1 Set transparency value Facelabels on of f off Show face labels Facelabelscolor Char k Color for face labels Facemode on off on Show faces Vertexlabels on off off Show vertex labels Vertexlabelscolor Char k Color for vertex labels Vertexmode on off off Show vertices The Build property determines if mphgeom build the geometry prior to display it If the Build property is set with a geometric object tag the geometry is built up to that object mphgeom only displays built geometry objects 204 CHAPTER 6 COMMAND REFERENCE mphgeom Example Load shell_diffusion mph from the Model Library model mphload shell_diffusion mph Plot the geometry mphgeom model Plot the geo
150. ins 1 for edges boundaries and 0 for points The selection also specifies the condition for geometric entities to be selected model selection lt seltag gt set condition condition where condition can be e inside to select all geometric entities completely inside the ball e intersects to select all geometric entities that intersect the ball default e somevertex to select all geometric entities where at least some vertex is inside the ball or e allvertices to select all geometric entities where all vertices are inside the ball Ball Selection Using MPHSELECTCOORDS The function mphselectcoords retrieves geometric entities enclosed by a ball To get the geometric entities enclosed by a ball of radius r0 with its center positioned at x0 y0 z0 enter the command idx mphselectcoords model lt geomtag gt lt x0 gt lt y0 gt lt z0 gt entitytype radius lt r0 gt where lt geomtag gt is the tag of geometry where the selection and ent itytype can be one of point edge boundary or domain The above function returns the entity indices list Use it to specify a feature selection or to create an explicit selection as described in Setting an Explicit Selection By default the function searches for the geometric entity vertices near these coordinates using the tolerance radius It returns only the geometric entities that have all vertices inside the search ball To include any ge
151. ins the node of the error and the second column contain the error message mphnavigator 251 mphsolinfo Purpose Get information about a solution object Syntax info mphsolinfo model info mphsolinfo model solname soltag Description object info mphsolinfo model solname soltag info mphsolinfo model returns information about the default solution returns information about the solution object soltag The function mphsolinfo accepts the following property value pairs TABLE 6 22 PROPERTY VALUE PAIRS FOR THE MPHSOLINFO COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Solname String Active solution Solution object tag object Dataset String Active Data set tag solution data set NU on off off Get info about number of solutions The returned value info is a structure with the following content TABLE 6 23 FIELDS IN THE INFO STRUCT FIELD CONTENT Solname Size Nummesh Sizes Soltype Solpar Sizesolvals Solvals Paramsweepnames Paramsweepvals NUsol NUreacf Solution name Size of the solution vector Number of meshes in the solution for automatic remeshing Size of the solution vector for each mesh and number of timesteps parameters for each mesh Solver type Stationary Parametric Time or Eigenvalue Name of the parameter Length of the parameter list Values of the parameters eigenvalues or timesteps Parametric sweep parameter names
152. ion The Selection Node e Coordinate Based Selections e Selection Using Adjacent Geometry e Displaying Selections a User Defined Selections in the COMSOL Multiphysics User s Guide See Also The links to features described outside of this user guide do not work in the PDF only from within the online help Important CHAPTER 3 The Selection Node Use a Selection node to define a collection of geometry entities in a central location in the model The selection can easily be accessed in physics or mesh features or during results analysis For example you can refer collectively to a set of boundaries that have the same boundary conditions which also have the same mesh size settings A selection feature can be one of these types e explicit to include entities explicitly defined by their definitions indices e ball to include entities that fall with a set sphere e box to include entities that fall within a set box Selection can also be combined by Boolean operations such as Union Intersection and Difference SETTING AN EXPLICIT SELECTION Create an explicit selection with the command model selection create lt seltag gt Explicit BUILDING MODELS To specify the domain entity dimension to use in the selection node enter model selection lt seltag gt geom sdim where sdim is the space dimension that represents the different geometric entities e 3 for domains e 2 for boundaries domains
153. ion e Evaluating an Expression Average e Evaluating a Minimum of Expression Extracting Data From Tables In the table node you can store the data evaluated with the COMSOL built in evaluation method see The Numerical Node Syntax Use the tag tbltag to extract the data stored in the table Enter tabl model result table lt tbltag gt getTableData fullprecision 5 This creates a java lang string array tabl that contains the data of the table tbltag The size of the array table is Nx1 where N is the number of the table line fullprecision is a Boolean expression to get the data with full precision To get the value of a specific row of the table enter tablline tabl lt i gt where lt i gt is the number of the desired row The variable tablline is a Mx java lang string array where M is the row number in the table To obtain the table header enter EXTRACTING RESULTS II7 118 header model result table lt tbitag gt getColumnHeaders where header is a Mx java lang string array and M is the row number of the table To get the table as a double array use the methods getReal and get Imag tablReal model result table lt tbltag gt getReal tablImag model result table lt tbitag gt getImag tablReal and tablImag are available at the MATLAB workspace as NxM arrays where N is the number of lines and M the number of rows of the table To get the table data at a specific row use the commands
154. ions are available to access results at node points or arbitrary locations You can also obtain low level information about the extended mesh such as finite element mesh coordinates connection information between the elements and nodes Extracted data are available as MATLAB variables ready to be used with any MATLAB function See the sections Extracting Results and Retrieving Xmesh Information INTRODUCTION CREATE CUSTOM INTERFACES FOR MODELS Use the MATLAB Guide functionality to create a user defined graphical interface that is combined with a COMSOL model Make your models available for others by creating graphical user interfaces tailored to expose settings and parameters of your choice ABOUT LIVELINK FOR MATLAB 9 10 Help and Documentation CHAPTER I In this section e Getting Help e Where Do I Access the Documentation and the Model Library e Typographical Conventions Getting Help COMSOL and LiveLink for MATLAB contain several sources of help and information THE INTRODUCTION TO LIVELINK FOR MATLAB To get started with LiveLink for MATLAB it is recommended that you read the Introduction to LiveLink for MATLAB It contains detailed examples about how to get you started with the product ONLINE DOCUMENTATION AND OTHER RESOURCES e Access the on line documentation with the function mphdoc e Read this user guide to get detailed information about the different parts of the model object and how these are
155. is provided In case of the presence ofa solver step node in the solver sequence the load vector correspond then to the residual of the problem Load heat_convection_2d mph from the Model Library model mphload heat_convection_2d mph Extract the stiffness matrix and the load vector str mphmatrix model sol1 out K L initmethod init Plot the sparsity of the matrix spy str K Extract the eliminated system str mphmatrix model sol1 out Kce Lc initmethod init Compare the sparsity of both system matrices non eliminated b and eliminated one r hold on spy str Kce r CHAPTER 6 COMMAND REFERENCE mphmatrix Load heat_radiation_ld mph from the model library model mphload heat_radiation_id mph Extract the eliminated residual str mphmatrix model sol1 out Lc See also mphstate mphxmeshinfo 229 mphmax 230 CHAPTER 6 Purpose Syntax Description Perform maximum of expressions v1 vn mphmax model e1 en edim v1 vn unit mphmax model e1 en edim v1 vn mphmax model e1 en edim evaluates the maximum of the string expressions e1 en and returns the result in N matrices v1 Vvn with M rows and P columns M is the number of inner solution and P the number of outer solution used for the evaluation edim defines the element dimension line surface volume or as an integer value
156. itytype can be one of point edge boundary or domain The above function returns the entity indices list Use it to specify a feature selection or to create an explicit selection as described in Setting an Explicit Selection By default the function searches for the geometric entity vertices near these coordinates using the tolerance radius It returns only the geometric entities that have all vertices inside the box or rectangle To include any geometric entities in the selection that have at least one vertex inside the search ball set the property include to any idx mphselectbox model lt geomtag gt lt x0 gt lt x1 gt lt y0 gt lt yl1 gt lt z0 gt lt z1 gt entitytype include any In case the model geometry is finalized as an assembly pair you have distinct geometric entities for each part of the assembly Specify the adjacent domain index to avoid selection of overlapping geometric entities Set the adj number property with the domain index idx mphselectbox model lt geomtag gt lt x0 gt lt x1 gt lt y0 gt lt yl gt lt z0 gt lt z1 gt entitytype adjnumber lt idx gt where lt idx gt is the domain index adjacent to the desired geometric entities Selection Using Adjacent Geometry Another approach to select geometric entities is to define the adjacent object For example select edges adjacent to a specific domain or boundaries that are adjacent to a specific point
157. ize 3 5 Add an interpolation curve feature ici geomi feature create ic1 InterpolationCurve 6 Use the variable p for the data points ict set table p WORKING WITH GEOMETRY 47 7 Specify a closed curve ici set type closed 8 Plot the geometry with the mphgeom command mphgeom model 0 5 CREATING GEOMETRY FROM IMAGE DATA Use the function mphimage2geom to create geometry from image data The image data format can be M by N array for a grayscale image or M by N by 3 array for a true color image E See the MATLAB function imread to convert an image file to image data Note Ifyou specify the image data and the level value that represents the geometry contour you want to extract the function mphimage2geom returns a model object with the desired geometry model mphimage2geom lt imagedata gt lt level gt where imagedatais a C array containing the image data and 1eve1 is the contour level value used to generate the geometry contour 48 CHAPTER 3 BUILDING MODELS Specify the type of geometry object generated model mphimage2geom lt imagedata gt lt level gt type type where type is solid and generates a solid object closed generates a closed curve object or open generates an open curve geometry object Use the property curvetype to specify the type of curve used to generate the geometry object model mphimage2geom lt imagedata gt lt level
158. l lt expr gt edim edim where edimis either a string or a positive integer such as point 0 edge 1 boundary 2 or domain 3 The default settings correspond to the model EXTRACTING RESULTS II9 120 geometry space dimension When using a lower space dimension value make sure that the evaluation point coordinates dimension has the same size EI Use the function mphevalpoint to evaluate expressions at geometric points see Evaluating an Expression at Geometry Vertices Note e solnum specify the inner solution number for data evaluation Inner solutions are generated for the following analysis types time domain frequency domain eigenvalue or stationary with continuation parameters pd mpheval model lt expr gt solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index lt solnum gt can also be end to evaluate the expression for the last inner solution By default the evaluation is done using the last inner solution e outersolnun specify the outer solution number for data evaluation Outer solutions are generated with parametric sweeps pd mpheval model lt expr gt outersolnum lt outersolnum gt where lt outersolnum gt is a positive integer corresponding to the outer solution index The default setting uses the first outer solution for the data evaluation e To evaluate the expression data at a specific time use
159. l Tree section Click Filter to filter the reduce the methods list to the one that returns simple information Select a method in the list to get its associated syntax at the button of the Methods section Use the Copy button to copy the syntax to the clipboard Navigating The Model Object At The Command Line Retrieve model object information such as tags for nodes and subnodes of a COMSOL model object at the MATLAB prompt using the command mphmodel To get the list of the main feature nodes and the tags of the model object mode1 enter the command mphmodel model To list the subfeature of the node type model feature enter the command mphmodel model feature To list the subfeature node of the feature node model feature lt ftag gt enter mphmodel model feature lt ftag gt Use the flag struct to return the model object information to MATLAB structure str mphmodel model feature struct str is a MATLAB structure and the fields consist of each feature node associated to the node model feature CHAPTER 4 WORKING WITH MODELS Finding Model Expressions Each model object contains predefined expressions that depend on the physics interface used in the model The function mphsearch starts a MATLAB GUI that displays the list of all the expressions constants solution variables or parameters available in the model object E mphsearch Search CO
160. l equation To retrieve information about the physics interface create an info object info model physics ht feature solid1 featureInfo info From the info object access the weak form equation by entering infoTable info getInfoTable Weak This returns a string variable that contains both the name of the weak equation variable and the equation of the physics implemented in the weak form Enter the command list infoTable which results in the output list java lang String 1x159 char root mod1 ht solid1 weak 1 Material Domain 1 The output shows that the physics is defined with the weak expression available in the variable list 1 Enter list 1 to get the weak equation as a string variable The result of this command is ans ht kK_eFFxXx Txtht k_effxy Tyt ht k_effxz Tz test Tx ht k_effyx Txtht k_effyy Tyt ht k_effyz Tz test Ty ht k_effzx Tx ht k_eff zy Tytht k_effzz Tz test Tz To access the equation in the node root mod1 ht solid1 weak 1 for example to modify the equation and lock the expression run the commands equExpr 400 W m K Tx test Tx Ty test Ty Tz test Tz info lock list 2 equExpr These commands set the heat conductivity to a constant value directly within the heat balance equation Adding Global Equations To add a global equation in the model use the command BUILDING MODELS model physics create lt odestag gt GlobalEquati
161. l result create lt pgtag gt sdim select the string lt pgtag gt to identify the plot group and the integer sdim to set the space dimension 1 2 or 3 of the group To add a plot to a plot group use the syntax model result lt pgtag gt feature create lt ftag gt plottype where the string lt ftag gt identifies the plot and the string plot type defines its type Plots can have different attributes that modify the display For instance the Deformation attribute deforms the plot according to an evctor quantity the Height Expression attribute introduces 3D height on a 2D table surface plot and the Filter BUILDING MODELS attribute filters the plot using a logical expression The type of plot determines which attributes are available Add an attribute to a plot by the command model result lt pgtag gt feature lt ftag gt feature create lt attrtag gt attrtype where attrtype is a string that defines the attribute type For a list of available plot types and corresponding attribute types see a Results in the COMSOL Java API Reference Guide Also see See Also model result in this guide Displaying The Results DISPLAY PLOT GROUPS Use the command mphplot to display a plot group available from model object For example to display the plot group lt pgtag gt enter mphplot model lt pgtag gt This renders the graphics in a MATLAB figure window In addition you can plot results in a COMSOL Gra
162. ll Solution for evaluation all end T Double array Time for evaluation Unit String cell Unit to use for the array evaluation The property Dataset controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on solution data sets When the property Phase is used the solution vector is multiplied with exp i phase before evaluating the expression The expressions ei are evaluated for one or several solutions Each solution generates an additional row in the output data array di The property Solnum and t control which solutions are used for the evaluations The Solnum property is available when the data set has multiple solutions for example in the case of 213 mphglobal 214 Example See also parametric eigenfrequency or time dependent solutions The t property is available only for time dependent problems If Solnum is provided the solutions indicated by the indices provided with the Solnum property are used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated For time dependent problems the variable t can be used in the expressions ei The value of t is the interpolation time when the property t is provided and the time for the solution when Solnum is used Similarly Lambda and the parameter are available as eigenvalues for eigenvalue problems and as
163. lt seltag gt can also be a positive integer array that corresponds to the domain index list The default selection is all domains where the expression is defined If the evaluation point does not belong to the specified domain selection the output value is NaN EXTRACTING RESULTS 136 e solnum specify the inner solution number for data evaluation Inner solutions are generated for the following analysis types time domain frequency domain eigenvalue or stationary with continuation parameters data mphmin model lt expr gt edim solnum lt solnum gt where lt solnum gt is an integer array corresponding to the inner solution index You can also set the property solnumto end to evaluate the expression for the last inner solution By default the evaluation is done using the last inner solution e outersolnum specify the outer solution number for data evaluation Outer solutions are generated with parametric sweeps data mphmin model lt expr gt edim outersolnum lt outersolnum gt where lt outersolnum gt is a positive integer array corresponding to the outer solution index The default setting uses the first outer solution for the data evaluation e To evaluate the expression data at a specific time use the property t data mphmin model lt expr gt edim t lt time gt where lt time gt is a double array The default value corresponds to all the stored time steps OUTPUT FORMAT The
164. lutions for example in the case of parametric eigenfrequency or time dependent solutions The t property is available only for time dependent problems If Solnum is provided the solutions indicated by the indices provided with the Solnum property are used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated Solnum is used to select the solution number when a parametric eigenvalue or time dependent solver has been used Outersolnum is used to select the outer solution number when a parametric sweep has been used in the study step node If the Matrix property is set to of f the output will be cell arrays of length P containing cell arrays of length M Load micromixer mph from the Model Library model mphload micromixer mph Find the mean x velocity u at the outlet boundary and get its unit flow unit mphmean model u surface selection 136 Load heat_transfer_axi mph from the Model Library model mphload heat_transient_axi mph Find the mean normal heat flux along the external boundaries Q mphmean model ht ndflux line selection 2 3 4 mphmax mphmin 233 mphmesh 234 Purpose Syntax Description Example See also Plot a mesh in a MATLAB figure window mphmesh model mphmesh model meshtag mphmesh model plots the mesh case in a MATLAB figure mphmesh model meshtag plots the mesh case meshtag in
165. ly Set System Matrices in the Model Use the function mphinputmatrix to set a linear matrix system to a model mphinputmatrix model lt str gt lt soltag gt lt soltypetag gt The above command set the matrices of a linear system stored in the MATLAB structure lt str gt into the model The linear system is associated to the solver sequence lt soltag gt and to be solved by the solver lt soltypetag gt mphinputmatrix only supports the solver types Stationary Eigenvalue and Time A valid structure lt str gt for a stationary solver includes the following fields FIELD DESCRIPTION K Stiffness matrix L Load vector M Constraint vector N Constraint Jacobian WORKING WITH MATRICES 145 146 A valid structure lt str gt for a time dependent or an eigenvalue solver includes the following fields EXPRESSION DESCRIPTION Stiffness matrix Load vector Constraint Jacobian K L M Constraint vector N D Damping matrix E Mass matrix You can also include the Constraint force Jacobian vector defined in the field NF Once the linear system is loaded in the model you can directly run the solver El The system matrices are not stored in the model once it is saved in the N MPH format or loaded to the COMSOL Desktop ote EXAMPLE SET A MODEL WITH A MODIFIED MATRIX SYSTEM This example deals with heat transfer in solids physics The geometry and physics settings is already set in
166. manually connecting MATLAB with a COMSOL server make sure you have the java opts at the MATLAB start up directory Disabling Model Feature Update For models that contain a large amount of physics feature nodes it may help to deactivate the model feature update while implementing the model object By default COMSOL updates the expression value for every feature node in the model which can take some time To disable the feature model update enter model disableUpdates true You need to enable the feature update prior to computing the solution unless the model expressions would not be updated according to the model settings This is also necessary if you are building a geometry or a mesh that depends on expressions To enable the feature model update enter model disableUpdates false Disabling The Model History If you are experiencing a slow down of the operation run in loop as the number iteration increases A possible reason is that the model history uses a significant amount memory that can no longer be accessible by the COMSOL operation You can disable the history recording to keep the model history information low To disable the model history enter the command model hist enable CHAPTER 4 WORKING WITH MODELS When the model history is disabled you no longer see the commands used to set up the model when saving it as an M file If you load the model object with the function mphload it automatically disa
167. match as long as any of the vertices are adjacent to the entity Load busbar mph from the Model Library 249 mphselectcoords 250 See also model mphload busbar mph Select the vertex near 0 095 0 0 1 n mphselectcoords model geom1 0 095 0 0 1 point Select the edge from 0 095 0 0 1 to 0 095 0 0 01 n mphselectcoords model geom1 0 095 0 0 1 0 095 0 0 01 edge Select edges that are adjacent to the points 0 095 0 0 1 and 0 095 0 0 01 n mphselectcoords model geomi1 0 095 0 0 1 0 095 0 0 01 edge include any Select boundaries that are adjacent to the points 0 09 0 0 1 and 0 09 0 0 015 with a search radius of 0 01 n mphselectcoords model geom1 0 09 0 0 1 0 09 0 0 boundary radius 0 01 mphgetadj mphgetcoords mphselectbox CHAPTER 6 COMMAND REFERENCE mphshowerrors Purpose Syntax Description See also Show messages in error nodes in the COMSOL model mphshowerrors model list mphshowerrors model mphshowerrors model shows the error and warning messages stored in the model and where they are located The output is displayed in the command window list mphshowerrors mode1 returns the error and warning messages stored in the model and where they are located in the Nx2 cell array list N corresponding to the number of errors or warning found in the model object The first column conta
168. message if all coordinates are outside the geometry Dataset String Auto Data set tag Edim point Geometry Element dimension for edge space evaluation boundary dimension domain O 1 2 3 Ext Value 0 1 Extrapolation control Matherr off on off Error for undefined operations or expressions Outersolnum Positive 1 Solution number for parametric integer sweep COMMAND REFERENCE mphinterp TABLE 6 11 PROPERTY VALUE PAIRS FOR THE MPHINTERP COMMAND PROPERTY PROPERTY DEFAULT DESCRIPTION VALUE Phase Scalar 0 Phase angle in degrees Recover off ppr off Accurate derivative recovery pprint Selection Positive all Selection list Integer array all Solnum Positive all Inner solutions for evaluation integer array all end T Double Time for evaluation array Unit String Unit to use for the evaluation Cell array The columns of the matrix coord are the coordinates for the evaluation points If the number of rows in coord equals the space dimension then coord are global coordinates and the property Edim determines the dimension in which the expressions are evaluated For instance Edim boundary means that the expressions are evaluated on boundaries in a 3D model If Edim is less than the space dimension then the points in coord are projected onto the closest point on a domain of dimension Edim If in addition the property Selection is given then the closest point on domain number S
169. metry and boundaries 2 4 6 8 10 16 17 18 29 and 20 in subplot ax subplot 1 2 1 mphgeom model geom1 parent ax edgecolor k edgelabels on alpha 0 5 edgelabelscolor b vertexmode on edgemode on ax subplot 1 2 2 mphgeom model geom1 parent ax entity boundary selection 2 2 10 16 20 See also mphmesh mphviewselection 205 mphgetadj Purpose Syntax Description Example See also Return geometry entity indices that are adjacent to other n mphgetadj model geomtag returntype adjtype adjnumber n mphgetadj model geomtag returntype adjtype adjnumber returns the indices of the adjacent geometry entities returntype is the type of the geometry entities whose index are returned adjtype is the type of the input geometry entity The entity type can be one of point edge boundary or domain following the entity space dimension defined below e domain maximum geometry space dimension e boundary maximum geometry space dimension 1 e edges l only for 3D geometry e point 0 Load busbar mph from the Model Library model mphload busbar mph Returns the indices of the domains adjacent to point 2 n mphgetadj model geom1 domain point 2 Returns the indices of the points adjacent to domains 2 and 3 n mphgetadj model geom1 point domain 2 3 mphgetcoords mphs
170. model If you have several meshes in your model specify the mesh to display using the command mphmesh model lt meshtag gt Use the parent property to specify the axes handle where to display the plot mphmesh model lt meshtag gt parent lt axes gt The following properties are also available to specify the vertex edge or face rendering edgecolor edgelabels edgelabelscolor edgemode facealpha facelabels facelabelscolor facemode meshcolor vertexlabels vertexlabelscolor vertexmode WORKING WITH MESHES 53 Mesh Creation Functions MESH SIZING PROPERTIES The Size attribute provides a number of input properties that can control the mesh element size such as the e maximum and minimum element size e element growth rate e resolution of curvature e resolution of narrow regions These properties are available both globally and locally There are several predefined settings that can be used to set a suitable combination of values for many properties To select one of these settings use the property hauto and pass an integer from 1 to 9 as its value to describe the mesh resolution e Extremely fine 1 e Extra fine 2 e Finer 3 e Fine 4 e Normal 5 e Coarse 6 e Coarser 7 e Extra coarse 8 e Extremely coarse 9 The default mesh setting is Normal 5 Q For details about predefined mesh size settings and mesh element size See Also parameters see Size in the COMSOL Java AP
171. model containing the geometry sequence to the COMSOL server WORKING WITH GEOMETRY 4l 42 Importing and Exporting Geometries and CAD Models from File With COMSOL Multiphysics you can import and export geometries in a variety of file formats COMSOL MULTIPHYSICS FILES A natural choice for storing geometries in 1D 2D and 3D is the native file format of COMSOL s geometry kernel mphtxt and mphbin EI The mphtxt or mphbin file formats are only used for geometry and mesh objects It is not the same as a Model MPH file mph Note 2D CAD FORMATS COMSOL Multiphysics supports import and export for the DXF file format a data interchange format of the CAD system AutoCAD Files can also be imported using the neutral GDS format The ECAD geometry file format requires either the AC DC Module MEMS Module or the RF Module See the ECAD Import Module User s Guide or go to http www comsol com products multiphysics for more information about Tip this and other products 3D CAD FORMATS It is possible to import surface meshes in the STL and VRML formats With a license for the CAD Import Module or one of the LiveLink products for CAD you can import most 3D CAD file formats Parasolid ACIS SAT STEP IGES Pro ENGINEER Autodesk Inventor and SolidWorks See the individual user guides for detailed information Retrieving Geometry Information To retrieve the detailed in
172. mple in a 3D model if evaluation is done on edges 1D elements Edim is 1 Similarly for boundary evaluation 2D elements Edim is 2 and for domain evaluation 3D elements Edim is 3 default in 3D Use Recover to recover fields using polynomial preserving recovery This techniques recover fields with derivatives such as stresses or fluxes with a higher theoretical convergence than smoothing Recovery is expensive so it is turned off by default The value pprint means that recovery is performed inside domains The value ppr means that recovery is also applied on all domain boundaries The property Refine constructs evaluation points by making a regular refinements of each element Each mesh edge is divided into Refine equal parts The property Smooth controls if the post data is forced to be continuous on element edges When Smooth is set to internal only elements not on interior boundaries are made continuous When the property Phase is used the solution vector is multiplied with exp i phase before evaluating the expression The expressions e1 en are evaluated for one or several solutions Each solution generates an additional row in the data fields of the post data output structure The property Solnum and t control which solutions are used for the evaluations The Solnum property is available when the data set has multiple solutions for example in the case of parametric eigenfrequency or time dependent solutions
173. n mphstate accepts the following property value pairs TABLE 6 24 PROPERTY VALUE FOR THE MPHSTATE COMMAND PROPERTY VALUE DEFAULT DESCRIPTION Out MA MB A B Output matrix C D Mc Null ud x0 Keepfeature off on off Keep the state space feature in the model Input String Input variables Output String Output variables Sparse off on off Return sparse matrices Initmethod init sol Use linearization point Initsol solname zero solname Solution to use for linearization Solmum Positive integer auto Solution number The property Sparse controls whether the matrices A B C D M MA MB and Null are stored in the sparse format The equations correspond to the system below ae McAx McBu y Cx Du where x are the state variables u are the input variables and y are the output variables 255 mphstate 256 Example A static linearized model of the system can be described by y D C McA 1McB u The full solution vector U can be then obtained from U Nullx ud u0 where Null is the null space matrix wd the constraint contribution and u0 is the linearization point which is the solution stored in the sequence once the state space export feature is run The matrices Mc and MA are produced by the same algorithms that do the finite element assembly and constraint elimination in COMSOL Multiphysics Me and MA are the same as the matrices D eliminated mass matrix and K Ke is the eliminated s
174. n the structure str stats data mphmeshstats model meshtag returns in addition the mesh data information such as vertex coordinates and definitions of elements in the structure data The output structure stats contains the following fields TABLE 6 16 FIELDS IN THE STATS STRUCTURE FIELD DESCRIPTION Meshtag Mesh case tag Isactive Is the mesh node active Hasproblems Does the mesh have problems Iscomplete Is the mesh built to completion Sdim Space dimension Types Cell array with type names Numelem Vector with the number of elements for each type Minquality Minimum quality Meanquality Mean quality Qualitydistr Quality distribution vector Minvolume Volume area of the smallest element Maxvolume Volume area of the largest element Volume Volume area of the mesh The output structure data contains the following fields TABLE 6 17 FIELDS IN THE DATA STRUCTURE FIELD DESCRIPTOIN Vertex Coordinates of mesh vertices 235 mphmeshstats 236 Example See also TABLE 6 17 FIELDS IN THE DATA STRUCTURE FIELD DESCRIPTOIN Elem Cell array of definition of each element type Elementity Entity information for each element type Load busbar mph from the Model Library model mphload busbar Show the mesh distribution in a figure stats mphmeshstats model bar linspace 0 1 20 stats qualitydistr Show the element vertices in a plot stats data mphmeshstats model
175. nal prompt start a COMSOL server with the command comsol server amp 2 In the same terminal window change the path to the COMSOL installation directory cd COMSOL_path mli 3 From that location start MATLAB without display and run the mphstart function in order to connect MATLAB to COMSOL matlab nodesktop mlnosplash r mphstart myscript You can get more information about how to connect MATLAB to a COMSOL server in Starting COMSOL with MATLAB on Windows Mac OSX Linux RUNNING MODELS IN BATCH MODE 14I Working with Matrices In this section e Extracting System Matrices e Set System Matrices in the Model e Extracting State Space Matrices Extracting System Matrices Extract the matrices of the COMSOL linearized system with the function mphmatrix To call the function mphmatrix specify a solver node and the list of the system matrices to extract str mphmatrix model lt soltag gt out out where lt soltag gt is the solver node tag used to assemble the system matrices and out is a cell array containing the list of the matrices to evaluate The output data str returned by mphmatrix is a MATLAB structure and the fields correspond to the assembled system matrices The system matrices that can be extracted with mphmatrix are listed in the table below EXPRESSION DESCRIPTION K Stiffness matrix L Load vector M Constraint vector N Constraint Jacobian D Damping matrix E Mass matrix NF Co
176. ncludes the COMSOL API Java with all necessary functions and methods to implement models from scratch For each operation you do in the COMSOL Desktop there is a corresponding command you can enter at the MATLAB prompt This is a simplified Java based syntax which does not require any knowledge of Java Available methods are listed in the COMSOL Java API Reference Guide The simplest way to learn this programing syntax is to save the model as an M file directly from the COMSOL Desktop You can read more about building a model using the command line in the section Building Models USE MATLAB FUNCTIONS IN MODEL SETTINGS Use LiveLink for MATLAB to set model properties with a MATLAB function For example define material properties or boundary conditions as a MATLAB routine that is evaluated while the model is solved This is described in the section Calling MATLAB Functions LEVERAGE MATLAB FUNCTIONALITY FOR PROGRAM FLOW Use the API syntax together with MATLAB functionality to control the flow of your programs For example implement nested loops using for or while commands or implement conditional model settings with if or switch statements You can also handle exceptions using try and catch Some of these operations are described in the sections Running Models in a Loop and Handling Errors and Warnings ANALYZE RESULTS IN MATLAB API wrapper functions included with LiveLink for MATLAB make it easy to extract data at the command line Funct
177. ng the circle from it col geom2 feature create co1 Compose co1 selection input set c1 sqi co1 set formula sqi c1 A selection object is used to refer to the input object The operators and correspond to the set operations union intersection and difference respectively The Compose operation allows you to work with a formula Alternatively use the Difference operation instead of Compose The following sequence of commands starts with disabling the Compose operation co1 active false dif1 geom2 feature create dif1 Difference dif1 selection input set sqi dif1 selection input2 set c1 Run the geometry sequence to create the geometry and plot the result geom2 run BUILDING MODELS mphgeom model geom2 0 8F O6fF O4p O27 0 24 0 4 H 0 6F Trimming Solids Continue with rounding the corners of the rectangle with the Fillet operation fili geom2 feature create fili Fillet fil1 selection point set difi 1 2 7 8 fil1 set radius 0 5 Run the sequence again geom2 run The geometry sequence is updated with rounded corners To view the result enter mphgeom model geom2 0 8F O6F O4p 0 2 F 0 2 0 4 H 0 66f WORKING WITH GEOMETRY 37 38 CHAPTER 3 CREATING A 2D GEOMETRY USING BOUNDARY MODELING Use the following commands to create six open curve segments that together form a closed
178. nning A COMSOL M file In Batch Mode e Running A COMSOL M file In Batch Mode Without Display The Batch Node Using the COMSOL Java API you can run model in loop See Adding a Job Sequence Running A COMSOL M file In Batch Mode To run in batch a M script that runs COMSOL Model start COMSOL with MATLAB at a terminal window with the following command comsol server matlab myscript where myscript is the M script saved as myscript m that contains the operation to run at the MATLAB prompt The COMSOL does not automatically save the model You need to make sure that the model is saved before the end of the execution of the script See Loading and Saving a Model You can also run the script in batch without the MATLAB desktop and the MATLAB splash Enter the command below comsol server matlab myscript nodesktop mlnosplash Running COMSOL with MATLAB in batch mode as described in this chapter requires that you have xterm installed on your machine If this is not the case see Running A COMSOL M file In Batch Mode Without Display CHAPTER 4 WORKING WITH MODELS Running A COMSOL M file In Batch Mode Without Display COMSOL with MATLAB requires that xterm is installed on the machine If this is not the case as it might be for a computation server a workaround is to connect manually MATLAB to a COMSOL server with the function mphstart The steps below describe how to run an M script that runs a COMSOL model Ina system termi
179. now edit the load vector for the dofs that belong to edge 21 the total applied power is 50 W ME L unique_idx 1 50 length unique_idx Now that the linear system has been modified you can set it back in the model mphinputmatrix model ME sol1 s1 Compute the solution of the added system model sol sol1 runAll Display the solution pgi model result create pg1 PlotGroup3D pg1 feature create surf1 Surface mphplot model pg1 rangenum 1 WORKING WITH MATRICES 149 150 Surface Ternperature K 360 350 340 330 220 310 300 Extracting State Space Matrices Use state space export to create a linearized state space model corresponding to a COMSOL Multiphysics model You can export the matrices of the state space form directly to the MATLAB workspace with the command mphstate THE STATE SPACE SYSTEM A state space system is the mathematical representation of a physical model The system consistent in an ODE linking input output and state space variable A dynamic system can be represented with the following system dx da Ax Bu y Cx Du An alternative representation of the dynamic system is Mex McAx McBu y Cx Du This form is more suitable for large systems because the matrices Mc and M4 usually become much more sparse than A If the mass matrix M is small it is possible to approximate the dynamic state space model with a static model where Mc 0
180. nstraint force Jacobian NP Optimization constraint Jacobian MP Optimization constraint vector MLB Lower bound constraint vector MUB Upper bound constraint vector Ke Eliminated stiffness matrix Le Eliminated load vector 142 CHAPTER 4 WORKING WITH MODELS EXPRESSION DESCRIPTION De Eliminated damping matrix Ec Eliminated mass matrix Null Constraint null space basis Nullf Constraint force null space matrix ud Particular solution ud uscale Scale vector Requires the Optimization Module SELECTING LINEARIZATION POINTS The default selection of linearization points for the system matrix assembly is the current solution of the solver node associated to the assembly If the linearization point is not specified when calling mphmatrix E COMSOL automatically runs the entire solver configuration before Note assembling and extracting the matrices Save time during the evaluation by manually setting the linearization point Use the initmethod property as in this command str mphmatrix model lt soltag gt out out initmethod method where method corresponds to the type of linearization point the initial value expression init or a solution sol To set the solution to use for the linearization point use the property initsol str mphmatrix model lt soltag gt out out initsol lt initsoltag gt where lt initsoltag gt is the solver tag to use for linearization
181. nstructions might say to click the Zoom Extents button K and this means that when you hover over the button with your mouse the same label displays on the COMSOL Desktop An italic font indicates the introduction of important terminology Expect to find an explanation in the same paragraph or in the Glossary The names of other user guides in the COMSOL documentation set also have an italic font The forward arrow symbol gt is instructing you to select a series of menu items in a specific order For example Options gt Preferences is equivalent to From the Options menu choose Preferences 14 CHAPTER I INTRODUCTION CONVENTION EXAMPLE Code monospace font A Code monospace font indicates you are to make a keyboard entry in the user interface You might see an instruction such as Enter or type 1 25 in the Current density field The monospace font also is an indication of programming code or a variable name Italic Code monospace An italic Code monospace font indicates user inputs and font Arrow brackets lt gt following the Code monospace or Code italic fonts parts of names that can vary or be defined by the user The arrow brackets included in round brackets after either a monospace Code or an italic Code font means that the content in the string can be freely chosen or entered by the user such as feature tags For example model geom lt tag gt where lt tag gt is the geom
182. nt swe1 meshi feature create swe1 Sweep swe1 selection geom 3 swe1 selection add 1 mesh1 run mphmesh model To obtain a torus leave the angles property unspecified the default value gives a complete revolution WORKING WITH MESHES 63 64 CHAPTER 3 Figure 3 8 3D prism mesh created with the Sweep feature EXTRUDING A MESH BY SWEEPING To generate a 3D prism mesh from the same 2D mesh by extrusion and then to plot it enter these commands model ModelUtil create Model geom1 model geom create geom1 3 wp1 geom1 feature create wp1 WorkPlane wp1 set planetype quick wp1 set quickplane xy ci wo1 geom feature create c1 Circle c1 set pos 2 0 ext1 geom1 feature create ext1 Extrude ext1 selection input set wp1 geom1 runAll meshi model mesh create mesh1 geom1 ftril meshi feature create ftriit FreeTri ftril selection geom geomi 2 ftril selection set 3 dist meshi feature create dis1 Distribution dis1 selection set 1 dis1 set type predefined BUILDING MODELS dis1 set elemcount 20 dis1 set elemratio 100 swe1 meshi feature create swe1 Sweep swe1 selection sourceface geom geom1 2 swe1 selection targetface geom geom1 2 meshi1 run mphmesh model The result is shown in Figure 3 9 With the properties elemcount and
183. ntegration or summation The default uses the appropriate method for the given expression e intorder specify the integration order data mphmean model lt expr gt edim intorder lt order gt where lt order gt is a positive integer The default value is 4 Evaluating a Minimum of Expression Use the function mphmin to evaluate the minimum of a given expression over an inner solution list To evaluate the minimum of the COMSOL expressions e1 en use the command mphmin as follows di dn mphmin model e1 en edim where edim isa string to define the element entity dimension volume surface or line edim can also be set as a positive integer value 3 2 or 1 respectively The output variables d1 dn are an NxP array where N is the number of inner solutions and P the number of outer solutions SPECIFY THE EVALUATION DATA The function mphmin supports the following properties to set the data of the evaluation to perform e dataset specify the solution data set to use in the evaluation data mphmin model lt expr gt edim dataset lt dsettag gt lt dsettag gt is the tag ofa solution data set The default value is the current solution data set of the model e selection specify the domain selection for evaluation data mphmin model lt expr gt edim selection lt seltag gt where lt seltag gt is the tag ofa selection node to use for the data evaluation
184. olnum property is available when the data set has multiple solutions for example in the case of parametric eigenfrequency or time dependent solutions The t property is available only for time dependent problems If Solnum is provided the solutions indicated by the indices provided with the Solnum property are used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated For time dependent problems the variable t can be used in the expressions ei The value of t is the interpolation time when the property t is provided and the time for the solution when Solnum is used Similarly Lambda and the parameter are available as eigenvalues for eigenvalue problems and as parameter values for parametric problems respectively Load shallow_water_equations mph from the Model Library model mphload shallow_water_equations mph Evaluate the elevation Z at point number 2 dat mphevalpoint model Z selection 2 Evaluate the maximum value of the elevation with respect to the time at point 2 dat mphevalpoint model Z selection 2 dataseries max Evaluate the maximum value of the elevation with respect to the time at point 2 dat mphevalpoint model Z selection 2 dataseries rms CHAPTER 6 COMMAND REFERENCE mphevalpoint See also mpheval mphglobal mphinputmatrix mphinterp 203 mphgeom Purpose Syntax Description Plot a geometry in a MATLAB f
185. olution will be stored in a matrix if the Matrix option is set to on Load falling _sand mph from the Model Library model mphload falling_sand mph Get the solution vector for the last time step default solution number u mphgetu model Get the solution vector and its derivative for solution number 9 and 10 u ut mphgetu model solnum 9 10 211 mphgetu See also mphsolinfo 212 CHAPTER 6 COMMAND REFERENCE mphglobal Purpose Syntax Description Evaluate global quantities d1 dn mphglobal model e1 en d1 dn unit mphglobal model e1 en d1 dn mphglobal model e1 en returns the results from evaluating the global quantities specified in the string expression e1 en d1 dn unit mphglobal model e1 en also returns the unit of the expressions e1 en unit is a nx1 cell array The function mphglobal accepts the following property value pairs TABLE 6 6 PROPERTY VALUE PAIRS FOR THE MPHGLOBAL COMMAND PROPERTY PROPERTY VALUE DEFAULT DESCRIPTION Complexfun off on on Use complex valued functions with real input Complexout off on off Return complex values Dataset String Active solution Data set tag data set Matherr off on off Error for undefined operations or expressions Outersolnum Positive 1 Solution number for integer parametric sweep Phase Scalar 0 Phase angle in degrees Solnum Integer vector a
186. olutions and Solver in the COMSOL Java See Also API Reference Guide CHAPTER 3 Run the Solver Sequence There are several ways to run the solver sequence run the entire sequence run up to a specified feature or run from a specified feature Use the methods run or runA11 to run the entire solver configuration node model sol lt soltag gt run model sol lt soltag gt runAll You can also use the method run lt ftag gt to run the solver sequence up to the solver feature with the tag lt ftag gt model sol lt soltag gt run lt ftag gt For those occasions when you want to continue solving a sequence use the method runFrom lt ftag gt to run the solver configuration from the solver feature with the tag lt ftag gt model sol lt soltag gt runFrom lt ftag gt Adding a Parametric Sweep In addition to the study step that defines a study type you can add to the study node a parametric sweep This is a study step that does not generate equations and can only be used in combination with other study steps You can formulate the sequence of problems that arise when some parameters are varied in the model To add a parametric sweep to the study node enter model study lt studytag gt feature create lt ftag gt Parametric where lt studytag gt is the tag of the study node where to include the parametric sweep defined with the tag lt ftag gt BUILDING MODELS To add one or se
187. olutions vectors stored NUreacf Number of reaction forces vectors stored NUadj Number of adjacency vectors stored NUfsens Number of functional sensitivity vectors stored NUsens Number of forward sensitivity vectors stored The batch field is a a structure including the following fields BATCH FIELDS DESCRIPTION type The type of batch psol Tag of the associated solver node 156 CHAPTER 4 WORKING WITH MODELS BATCH FIELDS DESCRIPTION sol Tag of the stored solution associated to psol seq Tag of the solver sequence associated to psol Extracting Solution Vector Extract the solution vector with the function mphgetu enter U mphgetu model where U is an Nx double array with N the number of degrees of freedom of the COMSOL model You can refer to the function mphxmeshinfo to receive the dof name or a the node coordinates in the solution vector see Retrieving Xmesh See Also Information SPECIFYING THE SOLUTION Change the solver node to extract the solution vector with the property solname U mphgetu model soltag lt soltag gt where lt soltag gt is the tag of the solver node For solver settings that compute for several inner solutions select the inner solution to use with the solnum property U mphgetu model solnum lt solnum gt where lt solnum gt a positive integer vector that corresponds to the solution number to use to extract the solution vector For time de
188. ometric entities in the selection that have at least one vertex inside the search ball set the property include to any idx mphselectcoords model lt geomtag gt lt x0 gt lt y0 gt lt z0 gt entitytype radius lt r0 gt include any In case the model geometry is finalized as an assembly you have distinct geometric entities for each part of the assembly pair Specify the adjacent domain index to avoid selection of any overlapping geometric entities Set the adjnumber property with the domain index idx mphselectcoords model lt geomtag gt lt x0 gt lt y0 gt lt z0 gt entitytype radius lt r0 gt adjnumber lt idx gt 92 CHAPTER 3 BUILDING MODELS where lt idx gt is the domain index adjacent to the desired geometric entities DEFINING A BOX SELECTION NODE The Box selection node is defined by two diagonally opposite points of a box in 3D or rectangle in 2D Box Selection Using the COMSOL API This command adds a box selection to the model object model selection create lt seltag gt Box To specify the points lt x0 gt lt y0 gt lt z0 gt and lt x1 gt lt y1 gt lt z1 gt enter model selection lt seltag gt set xmin lt x0 gt model selection lt seltag gt set ymin lt y0 gt model selection lt seltag gt set zmin lt z0 gt model selection lt seltag gt set xmax lt x1 gt model selection lt seltag gt set ymax lt y1 gt model
189. on off on Squeeze singleton dimensions T Double array Time for evaluation The property Dataset controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on Solution Data Sets The mean of expressions e1 n is evaluated for one or several solutions Each solution generates an additional column in the returned matrix The property Solnum and t control which solutions are used for the evaluation The Solnum property is available when the data set has multiple solutions for example in the case of parametric eigenfrequency or time dependent solutions The t property is 237 mphmin 238 Example See also available only for time dependent problems If Solnum is provided the solutions indicated by the indices provided with the Solnum property are used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated Solnum is used to select the solution number when a parametric eigenvalue or time dependent solver has been used Outersolnum is used to select the outer solution number when a parametric sweep has been used in the study step node If the Matrix property is set to of f the output will be cell arrays of length P containing cell arrays of length M Load micromixer mph from the Model Library model mphload micromixer mph Find the minimum x v
190. on Integer All Set selection tag or entity number vector domains string all Smooth Internal internal Smoothing setting none everywhere Solnum Integer all Solutions for evaluation vector all end t Double Times for evaluation array The property Dataset controls which data set is used for the evaluation Data Sets contain or refer to the source of data for postprocessing purposes Evaluation is supported only on Solution Data Sets The property Edim decides which elements to evaluate on Evaluation takes place only on elements with space dimension Edim If not specified Edim equal to the space dimension of the geometry is used The setting is specified as one of the following strings point edge boundary or domain In previous versions it was only possible to specify Edim as a number For example in a 3D model if evaluation is done on edges 1D elements Edim is 1 Similarly for boundary evaluation 2D elements Edim is 2 and for domain evaluation 3D elements Edim is 3 default in 3D Use Recover to recover fields using polynomial preserving recovery This techniques recover fields with derivatives such as stresses or fluxes with a higher theoretical convergence than smoothing Recovery is expensive so it is turned off by default The value pprint means that recovery is performed inside domains The value ppr means that recovery is also applied on all domain boundaries 197 mpheval 198
191. on parameter value and lt ft_value gt is the function value lt i gt is the index 0 based in the interpolation table To use an external file change the source for the interpolation and specify the file where filename is the name including the path of the data file model func lt functag gt set source file model func lt functag gt set filename lt filename gt Several interpolation methods are available Choose the one to use with the command model func lt functag gt set interp method The string method can be set as one of the following alternatives e neighbor for interpolation according to the nearest neighbor method e linear for linear interpolation method e cubicspline for cubic spline interpolation method e piecewisecubic piecewise cubic interpolation method You can also decide how to handle parameter values outside the range of the input data by selecting an extrapolation method model func lt functag gt set extrap method The string method can be one of these values e const to use a constant value outside the interpolation data e linear for linear extrapolation method e nearestfunction to use the nearest function as extrapolation method e value to use a specific value outside the interpolation data model func in the COMSOL Java API Reference Guide See Also MODELING PHysics 89 90 Creating Selections In this sect
192. ons To define the name of the variable to be solved by the global equation enter model physics lt odetag gt set name lt idx gt lt name gt where lt idx gt is the index of the global equation and lt name gt a string with the name of the variable Set the expression lt expr gt of the global equation with model physics lt odetag gt set equation lt idx gt lt expr gt where lt expr gt is defined as a string variable Initial value and initial velocity can be set with the commands model physics lt odetag gt set initialValueU lt idx gt lt init gt model physics lt odetag gt set initialValueUt lt idx gt lt init_t gt where lt init gt and lt init_t gt are the initial value expression for the variable and its time derivative respectively EXAMPLE SOLVE AN ODE PROBLEM This example illustrates how to solve the following ODE in a COMSOL model ut e 1 0 2 u0 0 u0 20 model ModelUtil create Model ge model physics create ge GlobalEquations ge1 ge feature gei ge1 set name 1 1 u ge1 set equation 1 1 utt 0O 5 ut 1 ge1 set initialValueU 1 1 u0 ge1 set initialValueUt 1 1 u0t model param set u0 0 model param set uOt 20 std1 model study create std1 std1 feature create time Transient std1 feature time set tlist range 0 0 1 20 std1 run MODELING PHysics 87 88
193. or Cluster As for a solver sequence you need to attach the job sequence to an existing study node this is done with the command model batch lt batchtag gt atached lt studytag gt where lt studytag gt is the tag of the study node For each job type such as parametric batch or cluster job can be defined with specific properties Use the Set method to add a property to the batch job model batch lt batchtag gt set property lt value gt COMPUTING THE SOLUTION 10l 102 Q You can get the list of the properties in model batch in the COMSOL See Also Java API Reference Guide To run the batch sequence use the run method model batch lt batchtag gt run Plot While Solving With the Plot While Solving functionality you can monitor the development of the computation by updating predefined plots during the computation Since the plots are displayed on a COMSOL graphics window start COMSOL with MATLAB using the graphics mode Q See the COMSOL Multiphysics Installation and Operations Guide to See Also start COMSOL with MATLAB with the graphics mode CHAPTER 3 To activate Plot While Solving enter the command model study lt studytag gt feature lt studysteptag gt set plot on where lt studytag gt and lt studysteptag gt refer to the study node and study step respectively Specify the plot group to plot by setting the plot group tag model study lt studytag
194. ord lt coord gt with unit is a 1xN cell array where N is the number of expressions to evaluate Include the imaginary part in the data evaluation with the property complexout data mphinterp model lt expr gt coord lt coord gt complexout on To return an error if all evaluation points are outside the geometry set the property coorderr to on data mphinterp model lt expr gt coord lt coord gt coorderr on By default the function returns the value NaN SPECIFY THE EVALUATION QUALITY With the property recover you can specify the accurate derivative recovery data mphinterp model lt expr gt coord lt coord gt recover recover where recover is either ppr pprint or off the default Set the property to ppr to perform recovery inside domains or set to pprint to apply recovery to all domain boundaries Because the accurate derivative processing takes time the property is disabled by default OTHER EVALUATION PROPERTIES Set the unit property to specify the unit of the evaluation data mphinterp model lt expr gt coord lt coord gt unit lt unit gt where unit is a cell array with the same size as expr To not use complex value functions with real inputs use the property complexfun CHAPTER 4 WORKING WITH MODELS data mphinterp model lt expr gt coord lt coord gt complexfun off The default value uses complex value functions with real inputs Use the propert
195. pendent and continuation analyses the default value for the solnum property is the last solution number For an eigenvalue analysis it is the first solution number A model can contain different types of solution vectors the solution of the problem the reaction forces vector the adjoint solution vector the functional sensitivity vector or the forward sensitivity In mphgetu you can specify the type of solution vector to extract with the type property U mphgetu model type type EXTRACTING SOLUTION INFORMATION AND SOLUTION VECTOR 157 158 where type is one of the following strings sol reacf adj or sens to extract the solution vector the reaction forces the functional sensitivity or the forward sensitivity respectively OUTPUT FORMAT mphgetu returns the default the solution vector Get the time derivative of the solution vector Udot by adding a second output variable U Udot mphgetu model In case the property solnum is set as a 1x M array and the solver node only uses one mesh to create the solution the default output is an NxM array where N is the number of degrees of freedom of the model Otherwise the output U is a cell array that contains each solution vector If you prefer to have the output in a cell array format set the property matrix to off U mphgetu model solnum lt solnum gt matrix off CHAPTER 4 WORKING WITH MODELS Retrieving Xmesh Information
196. phics window if you start COMSOL with MATLAB in graphics mode To do this for a plot group lt pgtag gt enter mphplot model lt pgtag gt server on Q See the COMSOL Multiphysics Operations and Installation Guide to start COMSOL with MATLAB in graphics mode See Also Another way to plot in a COMSOL Graphics Window is to use the run method model result lt pgtag gt run E Plotting in a COMSOL Graphics window is not supported on Mac OS Note ANALYZING THE RESULTS 105 106 The default settings for plotting ina MATLAB figure do not display the color legend To include the color legend in a figure use the property rangenum mphplot model lt pgtag gt rangenum lt idx gt where the integer lt idx gt identifies the plot for which the color legend should be displayed EXTRACT PLOT DATA In some situation it can be useful to extract data from a plot for example if you to manually edit the plot as it is allowed in MATLAB To get a cell array dat which contains the data for each plot feature available in the plot group lt pgtag gt type dat mphplot model lt pgtag gt PLOT EXTERNAL DATA Using the function mphplot you can also plot data that you specify directly as an input argument The supported data format is according to the structure provided by the function mpheval This allows you to plot data that you have first extracted from the model then modified in MATLAB on the model
197. pper limits for both nu and x In the Plot Parameters table set the first row which corresponds to the first argument nu of the Lower limit column to 0 and the Upper limit column to 5 and set the second row corresponding of x of the Lower limit column to 0 and the Upper limit column to 10 THE MATLAB FUNCTION FEATURE NODE 18 182 Lower limit Upper limit 5 10 the Plot button to get this plot eh Graphies _ o QQAQR be ke tfo es Setting the Function Directory Path in MATLAB To be able to run a model that use an external MATLAB function the path directory of the function has to be set in MATLAB before it is called by COMSOL to evaluate the function To proceed you have three options to set the directory path in MATLAB e Save the model MPH file in the same directory as for the M functions CHAPTER 5 CALLING MATLAB FUNCTIONS e Set the system environment variable COMSOL_MATLAB_PATH with the M functions directory path e Use the Set Path window available in the MATLAB desktop under the File menu Adding a MATLAB Function with the COMSOL API Java Syntax To add a MATLAB feature node to the COMSOL model using the COMSOL API enter the command model func create lt ftag gt MATLAB Define the function name and function arguments with the command model func lt ftag gt setIndex funcs lt function_name gt 0 0 model func lt ftag gt setIndex funcs lt arglist
198. r tag to use for a linearization point You can also set the initsol property to zero which corresponds to using a null solution vector as a linearization point The default is the current solver node where the assemble node is associated For continuation time dependent or eigenvalue analyses you can set which solution number to use as a linearization point Use the solnum property str mphstate model lt soltag gt input lt input gt output lt output gt out out solnum lt solnum gt CHAPTER 4 WORKING WITH MODELS where lt solnum gt is an integer value corresponding to the solution number The default value is the last solution number available with the current solver configuration EXAMPLE To illustrate how to use the mphstate function to extract the state space matrices of the model heat_transient_axi from the COMSOL Multiphysics Model Library To be able to extract the state space matrices you need to do some modifications to an existing model First create a parameter TO that is set as the external temperature model mphload heat_transient_axi model param set Tinput 1000 degC model physics ht feature temp1 set TO 1 Tinput Then create a domain point probe pdomi model probe create pdom1 DomainPoint pdom1 model mod1 pdom1 setIndex coords2 0 28 0 0 pdom1 setIndex coords2 0 38 0 1 Extract the matrices of the state space system
199. rameter range of an edge use the edgeParamRange N method For example to get the length of edge number 3 enter geom1 edgeParamRange 3 To get the coordinate and the curvature data along a specified edge enter geom1 edgexX 2 0 5 geom1 edgeCurvature 2 0 5 There are also methods for getting information about the internal representation of the geometry For example the coordinates of the geometry vertices geom1 getVertexCoord To fetch geometry information from elements in the geometry sequence enter geom1 obj b1k1 getNBoundaries Modeling with a Parameterized Geometry COMSOL has built in support for parameterized geometries Parameters can be used in most geometry operations To exemplify parameterizing a geometry the following script studies the movement of a circular source through two adjacent rectangular domains model ModelUtil create Model model param set a 0 2 geom1 model geom create geom1 2 ri geom1 feature create ri1 Rectangle r1 set size 0 5 1 r1 set pos 0 0 r2 geom1 feature create r2 Rectangle r2 set size 0 6 1 r2 set pos 0 5 0 c1 geom1 feature create c1 Circle c1 set r 0 1 BUILDING MODELS c1 set pos a 0 5 geom1 run mphgeom model Og9P 0 88f 0 7 F O6F 05F 0 4F O37 O27 O17 Change the position of the circle by changing the value of parameter a model param set a 0 5 geom1 run
200. re used If t is provided solutions are interpolated If neither Solnum nor t is provided all solutions are evaluated For time dependent problems the variable t can be used in the expressions ei The value of t is the interpolation time when the property t is provided and the time for the solution when Solnum is used Similarly Lambda and the parameter are available as eigenvalues for eigenvalue problems and as parameter values for parametric problems respectively The unit property defines the unit of the integral if a inconsistent unit is entered the default unit is used In case of multiple expression if the unit property is defined with a string the same unit is used for both expressions To use different units set the property with a cell array In case of inconsistent unit definition the default unit is used instead Solnum is used to select the solution number when a parametric eigenvalue or time dependent solver has been used Outersolnum is used to select the outer solution number when a parametric sweep has been used in the study step node Load micromixer mph from the Model Library model mphload micromixer mph Integrate the x velocity u at the outlet boundary and get its unit flow unit mphint2 model u surface selection 136 Load heat_transfer_axi mph from the Model Library model mphload heat_transient_axi mph Integrate the normal heat flux along the external boundaries using surface
201. rface MODELING PHYSICS 83 84 CHAPTER 3 mphplot model pgi rangenum 1 Surface Temperature K The Material Syntax In addition to changing material properties directly inside the physics interfaces materials available in the entire model can also be created Such a material can be used by all physics interfaces in the model Create a material using the syntax model material create lt mattag gt where lt mattag gt is a string that you use to refer to a material definition A Material is a collection of material models where each material model defines a set of material properties material functions and model inputs To add a material model use the syntax model material lt mattag gt materialmodel create lt mtag gt where lt mattag gt is the string identifying the material defined when creating the material The string lt mtag gt refers to the material model To define material properties for the model set the property value pairs by entering BUILDING MODELS model material lt mattag gt materialmodel lt mtag gt set property lt value gt E model material in the COMSOL Java API Reference Guide See Also EXAMPLE CREATE A MATERIAL NODE The section Example Implement and Solve a Heat Transfer Problem showed how to change a material property inside a physics interface This example shows how to define a material available globally in the model These steps as
202. rix 150 materials 84 mesh advancing front 57 converting 72 copying 70 creating a quad mesh 58 creating boundary layers 66 Delaunay 57 getting information about 76 importing 73 refining 69 mesh resolution 54 meshing sequences 52 Model Builder 26 Model Library 12 INDEX 263 264 INDEX model object 26 ModelUtil 27 modifying equations 85 MPH files 13 NASTRAN files 73 NASTRAN mesh 73 native file formats 42 node point coordinates 119 no slip boundary condition 66 parameterized geometries 44 physics interfaces 81 plot groups syntax for 104 rectangle 36 refining meshes 69 reports 110 results analysis 104 results evaluation 109 sequences of operations 26 set operations 36 simplex elements 69 solver configurations syntax for 99 sparsity of matrix 228 squeezed singleton 126 state space matrices example of extracting 153 structured meshes 59 study syntax for 97 summary of commands 188 sweeping to revolve meshes 63 syntax for materials 84 for physics interfaces 81 technical support COMSOL 13 tolerance radius 92 trimming solids 37 typographical conventions 14 user community COMSOL 14 visualization 104 web sites COMSOL 14 weights of control polygon 38 NH COMSOL www comsol com
203. s command creates a model object Model on the COMSOL server and a MATLAB object model that is linked to the model object It is possible to have several model objects on the COMSOL server each with a different name To access each model object requires different MATLAB variables linked to them and each MATLAB variable must have a different name Create a MATLAB variable linked to an existing model object with the method ModelUtil model For example to create a MATLAB variable mode1 that is linked to the existing model object Model on the COMSOL server enter the command THE MODEL OBJECT 27 28 model ModelUtil model Model To remove a specific model object use the method ModelUtil remove For example to remove the model object Model from the COMSOL server enter the command ModelUtil remove Model Alternatively remove all the COMSOL objects stored in the COMSOL server with the command ModelUtil clear List the names of the model objects available on the COMSOL server with the command list ModelUtil tags ACTIVATING THE PROGRESS BAR By default no progress information is displayed while running COMSOL with MATLAB To manually enable a progress bar and visualize the progress of operations such as loading a model creating a mesh assembling matrices or computing the solution enter the command ModelUtil showProgress true To deactivate the progress bar enter Model1Util showProgress false
204. s that wrap API functionality for greater ease of use The Model Object Methods The model object provides a large number of methods The methods are structured in a tree like way very similar to the nodes in the model tree in the Model Builder window on the COMSOL Desktop The top level methods just return references that CHAPTER 3 BUILDING MODELS support further methods At a certain level the methods perform actions such as adding data to the model object performing computations or returning data Q Detailed documentation about model object methods is About General See Also Commands in the COMSOL Java API Reference Guide The links to features described outside of this user guide do not work in the PDF only from within the online help Important To locate and search all the documentation for this information in COMSOL select Help gt Documentation from the main menu and either Tp enter a search term or look under a specific module in the documentation I tree The General Utility Functionality The model object utility methods are available with the Model Util object These methods can be used for example to create or remove a new model object but also to enable the progress bar or list the model object available in the COMSOL server MANAGING THE COMSOL MODEL OBJECT Use the method ModelUtil create to create a new model object in the COMSOL server model ModelUtil create Model Thi
205. selection lt seltag gt set zmax lt z1 gt where lt x0 gt lt y0 gt lt z0 gt lt x1 gt lt y1 gt lt z1 gt are double values To specify the geometric entities levels use the command model selection lt seltag gt set entitydim edim where edim is an integer defining the space dimension value 3 for domains 2 for boundaries domains 1 for edges boundaries and 0 for points The selection also specifies the condition for geometric entities to be selected model selection lt seltag gt set condition condition where condition can be e inside to select all geometric entities completely inside the ball e intersects to select all geometric entities that intersect the ball default e somevertex to select all geometric entities where at least some vertex is inside the ball or e allvertices to select all geometric entities where all vertices are inside the ball Box Selection Using MPHSELECTBOX The function mphselectbox retrieves geometric entities enclosed by a box in 3D or rectangle in 2D To get the geometric entities of type ent itytype enclosed by the box defined by the points x0 y0 z0 and x1 y1 z1 enter the command CREATING SELECTIONS 93 94 CHAPTER 3 idx mphselectbox model lt geomtag gt lt x0 gt lt x1 gt lt y0 gt lt yl gt lt z0 gt lt z1 gt entitytype where lt geomtag gt is the geometry tag where the selection is applied and ent
206. several expressions are evaluated in mpheval additional field d2 d3 are available e p contains the node point coordinates information The number of rows in p is the number of space dimensions e t contains the indices to columns in pd p of a simplex mesh each column in pd t represents a simplex e ve contains the indices to mesh elements for each node points e unit contains the list of the unit for each evaluated expressions SPECIFY THE EVALUATION DATA The function mpheval supports the following properties to set the data of the evaluation to perform e dataset specify the solution data set to use in the evaluation pd mpheval model lt expr gt dataset lt dsettag gt lt dsettag gt is the tag ofa solution data set The default value is the current solution data set of the model Selection data set such as Cut point Cut line Edge Surface and so forth are not supported e selection specify the domain selection for evaluation pd mpheval model lt expr gt selection lt seltag gt where lt seltag gt is the tag ofa selection node to use for the data evaluation lt seltag gt can also be a positive integer array that corresponds to the domain index list The default selection is all domains where the expression is defined If the evaluation point does not belong to the specified domain selection the output value is NaN e edim specify the element dimension for evaluation pd mpheval mode
207. splay a plot of the function Click the Create Plot button 4 to create a plot group under the Results node To plot the function you first need to define limits for the arguments Expand the Plot Parameters section and enter the desired value in the Lower limit and Upper limit columns In the Plot Parameters table the number of rows correspond to the number of input arguments of the function The first input argument corresponds to the top row In case there are several functions declared in the Functions table only the function that has the same number of input arguments as the number of filled in rows in the Plot Parameters table is plotted CALLING MATLAB FUNCTIONS If several functions have the same number of input arguments the first function in the table from top to bottom is plotted Use the Move Up 4 and Move Down J buttons to change the order of functions in the table EXAMPLE DEFINE THE HANKEL FUNCTION Assume that you want to use MATLAB s Bessel function of the third kind Hankel function in a COMSOL model Add a MATLAB function node then define the following settings FUNCTION ARGUMENTS besselh nu x f MATLAB E Model Library nf Plot 54 Create Plot a v Functions Clear Functions Clear functions automatically before solving Function Arguments besselh nu x t p Function besselh Arguments nu x To plot the function you need first to define the lower and u
208. sume that the previous example has been followed Enter mat model material create mati1 The material automatically creates a material model def which can be used to set up basic properties For example use it to define the density and the heat capacity mat materialmodel def set density 400 mat materialmodel def set heatcapacity 2e3 To use the defined material in a model set the solid1 feature to use the material node Enter solid set k_mat 1 from_mat Modifying the Equations The equation defining the physics node can be edited with the method featureInfo info applied to a feature of the physics node physics lt phystag gt feature lt ftag gt where lt phystag gt and lt ftag gt identify the physics interface and the feature respectively info model physics lt phystag gt feature lt ftag gt featureInfo info Use the method getInfoTable type to return the tables available in the Equation View node infoTable info getInfoTable type where t ype defines the type of table to return It can have the value Weak to return the weak form equations Constraint to return the constraint types table or Expression to return the variable expressions table MODELING PHysics 85 86 CHAPTER 3 EXAMPLE ACCESS AND MODIFY THE EQUATION WEAK FORM This example continues from the Example Implement and Solve a Heat Transfer Problem and modifies the mode
209. t Stationary soli model sol create soli soli1 study std1 Extract the linear stationary matrix system in MATLAB str mphmatrix model sol1 out K L M N initmethod sol initsol zero Change the linear system by scaling the stiffness matrix str K str K 0 1 Set up the solver configuration for a stationary problem sti sol1 feature create st1 StudyStep st1 set studystep stat soli1 feature create s1 Stationary Insert the system matrix back to the model mphinputmatrix model str sol1 s1 Run the solver configuration model sol soli runAll mphmatrix mphxmeshinfo CHAPTER 6 COMMAND REFERENCE mphint2 Purpose Syntax Description Perform integration of expressions v1 V2 mphint2 model e1 en edim v1 V2 unit mphint2 model e1 en edim v1 vn mphint2 model e1 en evaluates the integrals of the string expressions e1 en and returns the result in N matrices v1 vn with M rows and P columns M is the number of inner solution and P the number of outer solution used for the evaluation edim defines the element dimension as a string Line surface volume or as an integer value v1 Vvn mphint2 model e1 en also returns the units of the integral in a 1xN cell array The function mphint2 accepts the following property value pairs TABLE 6 10 PROPERTY VALUE PAIRS FOR THE
210. t set height lt height_px gt where the positive integers lt width_px gt and lt height_px gt are the width and height size in pixels respectively to use for the animation DATA EXPORT In order to save data to an ASCII file create a Data node to the export method model result export create lt datatag gt Data Set the expression expr and the file name filenname and run the export model result export lt datatag gt setIndex expr lt expr gt 0 model result export lt datatag gt set filename lt filenname gt Set the export data format with the struct property model result export lt datatag gt set struct datastruct where datastruct can be set to spreadsheet or sectionwise See Data Formats in the COMSOL Multiphysics Reference Guide for See Also details about the data formats used in the exported data files To export the data in the specified file run the export node model result export lt datatag gt run ANIMATION PLAYER For transient and parametric studies an animation player can be generated to create interactive animations ANALYZING THE RESULTS III 112 The player displays the figure on a COMSOL Graphics window Make sure COMSOL with MATLAB is started with the graphics mode enabled Q To learn how to start COMSOL with MATLAB with the graphics mode See Also see the COMSOL Multiphysics Installation and Operations Guide CHAPTER 3
211. t where the longest edge of a triangle is bisected Some triangles outside the specified set might also be refined in order to preserve the triangulation and its quality In 3D the default refinement method is Longest while regular refinement is only implemented for uniform refinements In 1D the function always uses regular refinement where each element is divided into two elements of the same shape For stationary or eigenvalue PDE problems you can use adaptive mesh refinement at the solver stage with the solver step adaption See Note Adaption in the COMSOL Java API Reference Guide WORKING WITH MESHES 69 70 COPYING BOUNDARY MESHES Use the CopyEdge feature in 2D and the CopyFace feature in 3D to copy a mesh between boundaries EI It is only possible to copy meshes between boundaries that have the same shape However a scaling factor between the boundaries is allowed Note CHAPTER 3 The following example demonstrates how to copy a mesh between two boundaries in 3D and then create a swept mesh on the domain model ModelUtil create Model geom1 model geom create geom1 3 wp1 geom1 feature create wp1 WorkPlane wp1 set planetype quick wp1 set quickplane xy c1 wo1 geom feature create c1 Circle c1 set r 0 5 c1 set pos 1 0 revi geomi feature create revi Revolve revi set angle1 0 set angle2 180 rev1 selection
212. t information To establish the connection between the COMSOL Desktop and the COMSOL server enter a Username and a Password these are defined the first time you are connected to the COMSOL server 4 Enter the name of the model object to export the default name is Mode1 5 Click OK 6 In MATLAB create a link to the model object on the COMSOL server with the command model ModelUtil model Model If the model has been exported to the COMSOL server using a different name replace Model with the correct name of the exported model Use E the command ModelName ModelUtil tags to obtain the list of Note model objects available on the COMSOL server CHAPTER 3 BUILDING MODELS IMPORTING A MODEL IN THE COMSOL DESKTOP FROM MATLAB To import a model from a COMSOL server to the COMSOL Desktop from the File menu choose Client Server gt Import Model from Server This dialog box is similar to the Client Server gt Export Model to Server dialog box P Import Model from Server Server User Model Server localhost Username user Model Model Port 2036 Password eeecccscccccoces V Remember password Cancel Oo The COMSOL server may hold several models this is why it is mandatory to enter the name of the model for the import procedure Important THE MODEL OBJECT 31 32 Working with Geometry This section describes how to set up and run a geometry sequence In this section e The Geometr
213. the model The models are available in COMSOL 12 CHAPTER I INTRODUCTION as MPH files that you can open for further investigation You can use the step by step instructions and the actual models as a template for your own modeling and applications SI units are used to describe the relevant properties parameters and dimensions in most examples but other unit systems are available To open the Model Library select View gt Model Library Jf from the main menu and then search by model name or browse under a module folder name Click to highlight any model of interest and select Open Model and PDF to open both the model and the documentation explaining how to build the model Alternatively click the Help button E or select Help gt Documentation in COMSOL to search by name or browse by module The model libraries are updated on a regular basis by COMSOL in order to add new models and to improve existing models Choose View gt Model Library Update 1 to update your model library to include the latest versions of the model examples Ifyou have any feedback or suggestions for additional models for the library including those developed by you feel free to contact us at info comsol com CONTACTING COMSOL BY EMAIL For general product information contact COMSOL at info comsol com To receive technical support from COMSOL for the COMSOL products please contact your local COMSOL representative or send your questions to
214. the model and saved in the MPH format The Model MPH file comes with the COMSOL installation At the MATLAB prompt you will load the model and add an extra line heat source in the model directly in the system matrix by manually changing the load vector Then compute the solution of the modified system in COMSOL Load the base model MPH file and display the geometry model mphload model_tutorial_llmatlab mph mphgeom mode1 CHAPTER 4 WORKING WITH MODELS This results in the following MATLAB figure Draw a line to be used as line heat source in the model and plot the modified geometry b1 model geom geom1 feature create b1 BezierPolygon bi set p 1e 2 5e 2 1e 2 5e 2 1e 2 1e 2 mphgeom model geom1 edgelabels on alpha 0 5 In the figure below you can see that the added line as the index 21 Generate a mesh with a finer mesh settings mesh1 model mesh mesh1 meshi1 feature create ftet1 FreeTet mesh1 feature size set hauto 3 WORKING WITH MATRICES 147 mesh1 run mphmesh model Set the solver sequence associated to a stationary study node std1 model study create std1 std1 feature create stat Stationary soli model sol create sol1 sol1 study std1 sti soli feature create st1 StudyStep sti set studystep stat vi soli feature create v1 Variables vi set control stat sol1 fea
215. the option plot on server is active all active color range bar are displayed Load feeder_clamp mph from the Model Library model mphload feeder_clamp mph Plot the first plot group mphplot model pg1 Plot the first plot group with the color range bar 243 mphplot 244 See also CHAPTER 6 mphplot model pgi1 rangenum 1 Load fluid_valve mph and plot on server requires that you start COMSOL with MATLAB in graphics mode model mphload fluid_valve mph Plot the second plot group on server mphplot model pg2 server on Load busbar mph from the Model Library model mphload busbar mph Extract temperature and electric potential data in the busbar domain pd mpheval model T V selection 1 Plot the electric potential data using the disco color table mphplot pd index 2 colortable disco colortable mpheval COMMAND REFERENCE mphsave Purpose Save a COMSOL model Syntax mphsave model mphsave model filename Description mphsave model saves the COMSOL model object model mphsave model filename saves the COMSOL model object mode1 to the file named filename If the file name is not provided the model has to be saved previously on disk Ifthe file name does not provide a path the file is saved relatively to the current path in MATLAB The model can be saved as an mph file java file or as an m file The file extension determines which
216. the solver tag soltag associated to the solution object info mphsolinfo model soltag lt soltag gt If there are several solution data sets attached to the solver for example solution data sets with different selections specify the data set to use to get the solution object information with the dataset property info mphsolinfo model dataset lt dsettag gt where dsettag the tag of the solution data set to use EXTRACTING SOLUTION INFORMATION AND SOLUTION VECTOR 155 OUTPUT FORMAT The output info isa MATLAB structure The default fields available in the structure are listed in the following table FIELDS DESCRIPTION soltag Tag of the solver associated to the solution object study Tag of the study associated to the solution object size Size of the solution vector nummesh Number of mesh in the solution for automatic remeshing sizes Size of solution vector and inner parameters for each mesh soltype Solver type solpar Parameter name sizesolvals Length of parameter list solvals Inner parameter value paramsweepnames Outer parameter name paramsweepvals Outer parameter value batch Batch information dataset Tag of the solution data set associated to the solution object To get the information about the number of solutions set the property nu to on info mphsolinfo model nu on The info structure is added with the following fields FIELDS DESCRIPTION NUsol Number of s
217. tiffness matrix The matrices are produced from an exact residual vector Jacobian calculation that is differentiation of the residual vector with respect to the degrees of freedoms x plus an algebraic elimination of the constraints The matrix C is produced in a similar way that is the exact output vector Jacobian matrix plus constraint elimination The matrices MB and D are produced by a numerical differentiation of the residual and output vectors respectively with respect to the input parameters the algorithm systematically perturbs the input parameters by multiplying them by a factor 1 10 8 The input cannot be a variable constraint in the model Load heat_transient_axi mph from the Model Library model mphload heat_transient_axi mph Set the temperature condition using a parameter model param set Tinput 1000 degC tempi model physics ht feature temp1 temp1 set TO 1 Tinput Add a domain point probe at 0 28 0 38 pdom1 model probe create pdom1 DomainPoint pdom1 model mod1 pdom1 setIndex coords2 0 28 0 0 pdom1 setIndex coords2 0 38 0 1 Extract the state space matrix CHAPTER 6 COMMAND REFERENCE mphstate str mphstate model sol1 out MA MB C D input TO output mod1 ppb1 257 mphversion 258 Purpose Syntax Description See also Return the version number of COMSOL Multiphysics v mphversion v vm
218. ts In that case one can use the adjnumber property in order to identify the domain that the vertices should be adjacent to Load busbar mph from the Model Library model mphload busbar mph Find domains that are inside the selection box defined by 0 0 05 0 0 05 0 05 0 05 n mphselectbox model geomi 0 0 05 0 0 05 0 05 0 05 domain Find boundaries inside the selection box that are adjacent to domain number 1 n mphselectbox model geomi 0 0 05 0 0 05 0 05 0 05 boundary adjnumber 1 247 mphselectbox 248 See also Load ef fective_diffusivity mph from the Model Library model mphload effective_diffusivity mph Find the boundaries that are inside the selection rectangle defined by 3e 4 4e 4 4 5e 4 5 5e 4 n mphselectbox model geomi 38e 4 4e 4 4 5e 4 5 5e 4 boundary Find the boundaries that are inside the same selection rectangle n mphselectbox model geomi S3e 4 4e 454 5e 4 5 5e 4 point mphgetadj mphgetcoords mphselectcoords CHAPTER 6 COMMAND REFERENCE mphselectcoords Purpose Syntax Description Examplee Select geometric entity using point coordinates 5 ll mphselectcoords model geomtag coord entity n mphselectcoords model geomtag coord entity finds geometry entity numbers based on their vertex coordinates One or more coordinate may be provided The function searches for vertices n
219. ture create s1 Stationary Set the dependent variable discretization with linear shape function ht model physics ht ht prop ShapeProperty set order_temperature 1 1 You can now extract the matrices of the linear system associated to the solver sequence soli ME mphmatrix model sol1 Out K L M N initmethod sol initsol zero To retrieve the degrees of freedom that belong to edge 21 you need first to get the geometric mesh data stats data mphmeshstats model 148 CHAPTER 4 WORKING WITH MODELS With the mesh data structure data you can get the element indices that belong to edge 21 use the MATLAB find function to list all the indices elem_idx find data elementity 1 21 With the function mphxmeshinfo retrieve the finite element mesh information associated to solver sequence soll info mphxmeshinfo model soltag soli studysteptag v1 In the info structure you can get the DOFs indices that belong to the edge element defined with the indices elem_idx edgdofs_idx for i 1 length elem_idx edgdofs_idx edgdofs_ idx info elements edg dofs elem_idx i end edgdofs_idx may contains duplicate DOFs indices This is because you got the information at the element level the duplicate indices correspond to the connecting node between two adjacent elements First remove the duplicate entities unique_idx unique edgdofs_ idx You can
220. ucts tutorials e Knowledge Base www comsol com support knowledgebase Part No CM020008 Contents Chapter I Introduction About LiveLink for MATLAB Help and Documentation Getting Help Sha MGs CE Aun teres ans ate Where Do Access the Documentation and the Model Library Typographical Conventions Chapter 2 Getting Started The Client Server Architecture Running COMSOL with MATLAB Starting COMSOL with MATLAB on Windows Mac OSX Linux Connecting the COMSOL Server and MATLAB Manually Changing the MATLAB Version Calling a MATLAB Function from the COMSOL Desktop Chapter 3 Building Models The Model Object Important Notes About the Model Object The Model Object Methods The General Utility Functionality Loading and Saving a Model Exchanging Models Between MATLAB and the COMSOL aoa Working with Geometry The Geometry Sequence Syntax Displaying the Geometry Working with Geometry Sequences Exchanging Geometries with the COMSOL DEGN Importing and Exporting Geometries and CAD Models from File 10 10 lI 14 19 19 20 2l 23 26 26 26 27 28 29 32 32 33 34 4l 42 4 CHAPTER Retrieving Geometry Information Modeling with a Parameterized Geometry Images and Interpolation Data Working with Meshes The Meshing Sequence Syntax Displaying the Mesh Mesh Creation Functions Oo ion ware a Importing External Meshes
221. veral parameters to the sweep enter the command model study lt studytag gt feature lt ftag gt setIndex pname lt pname gt lt idx gt where lt pname gt is the name of the parameter to use in the parametric sweep and lt idx gt the index number of the parameter Set the lt idx gt to 0 to define the first parameter 1 to define the second parameter and so on Set the list of the parameter values with the command model study lt studytag gt feature lt ftag gt setIndex plistarr lt pvalue gt lt idx gt where lt pvalue gt contains the list of parameter values defined with either a string or with a double array and lt idx gt is the index number of the parameter and uses the same value as for the parameter name If there are several parameters listed in the parametric sweep node select the type of sweep by entering model study lt studytag gt feature lt ftag gt set sweeptype type where the sweep type type can be either filled or sparse referring to all combination or specified combinations of the parameter values respectively Adding a Job Sequence In the study node you can define a job sequence such as distributed parametric jobs batch jobs and cluster computing To create a batch node enter model batch create lt batchtag gt type where lt batchtag gt is the tag of the job sequence and type is the type of job to define It can be either Parametric Batch
222. w to set a MATLAB variable in the COMSOL model in The Set and SetIndex Methods The function is evaluated any time the model needs to be updated The model object cannot be called as an input argument of the M function a Calling MATLAB Functions See Also USING MATLAB VARIABLES IN MODEL SETTINGS lI5 CALLING MATLAB FUNCTIONS AT THE MATLAB PROMPT Use a MATLAB function to define a model property with the set method something Set property myfun lt arg gt where myfun is an M function defined in MATLAB The function is called only when the command is executed at the MATLAB prompt The argument of the function lt arg gt called may be MATLAB variables To include an expression value from the model object first extract it at the MATLAB prompt as described in Extracting Results The function myfun accepts the model object mode1 as an input argument as any MATLAB variable 116 CHAPTER 4 WORKING WITH MODELS Extracting Results Use LiveLink for MATLAB to extract at the MATLAB prompt the data computed in the COMSOL model A suite of wrapper functions is available to perform evaluation operations at the MATLAB prompt In this section e Extracting Data From Tables e Extracting Data at Node Points e Extracting Data at Arbitrary Points e Evaluating an Expression at Geometry Vertices e Evaluating an Integral e Evaluating a Global Expression e Evaluating a Global Matrix e Evaluating a Maximum of Express
223. xpressions e The field p contains node point coordinate information The number of rows in p is the number of space dimensions e The field t contains the indices to columns in p of a simplex mesh each column in t representing a simplex e The field ve contains indices to mesh elements for each node point e The field unit contains the list of the unit for each expression The function mpheval accepts the following property value pairs TABLE 6 1 PROPERTY VALUE PAIRS FOR THE MPHEVAL COMMAND PROPERTY PROPERTY DEFAULT DESCRIPTION VALUE Complexfun off on on Use complex valued functions with real input Complexout off on off Return complex values Dataonly off on off Only return expressions value Dataset String Data set tag Edim point Geometry Evaluate on elements with this edge space space dimension boundary dimension domain 0 1 2 3 Matherr off on of f Error for undefined operations or expressions Outersolnum Positive 1 Solution number for parametric integer sweep 196 CHAPTER 6 COMMAND REFERENCE mpheval TABLE 6 1 PROPERTY VALUE PAIRS FOR THE MPHEVAL COMMAND PROPERTY PROPERTY DEFAULT DESCRIPTION VALUE Pattern lagrange lagrange Specifies if evaluation takes place in gauss Lagrange points or in Gauss points Phase Scalar 0 Phase angle in degrees Recover off ppr off Accurate derivative recovery pprint Refine Integer 1 Refinement of elements for evaluation points Selecti
224. y Sequence Syntax e Displaying the Geometry e Working with Geometry Sequences e Exchanging Geometries with the COMSOL Desktop e Importing and Exporting Geometries and CAD Models from File e Retrieving Geometry Information e Modeling with a Parameterized Geometry e Images and Interpolation Data e Geometry Modeling and CAD Tools in the COMSOL Multiphysics a User s Guide See Also e Geometry in the COMSOL Java API Reference Guide T The links to features described outside of this user guide do not work in the PDF only from within the online help Important CHAPTER 3 The Geometry Sequence Syntax Create a geometry sequence using the syntax model geom create lt geomtag gt sdim where lt geomt ag gt is a string used to refer to the geometry The integer sdim specifies the space dimension of the geometry and it can be either 0 1 2 or 3 To add an operation to a geometry sequence use the syntax model geom lt geomtag gt feature create lt ftag gt operation BUILDING MODELS where lt geomtag gt is the string defined when the geometry is created The string lt ftag gt is used to refer to the operation EI For a list of geometry operations see About Geometry Commands in the COMSOL Java API Reference Guide Note To set the feature property with different values than the default use the set method model geom lt geomtag gt feature lt ftag gt set property lt value gt
225. y matherr to return an error for undefined operations or expressions data mphinterp model lt expr gt coord lt coord gt matherr on Evaluating an Expression at Geometry Vertices The function mphevalpoint returns the result of a given expression evaluated at the geometry vertices d1 dn mphevalpoint model e1 en where e1 en are the COMSOL expressions to evaluate The output d1 dn is a NxP double array where N is the number of evaluation points and P the length of the inner solution SPECIFY THE EVALUATION DATA The function mphevalpoint supports the following properties to set the data of the evaluation to perform e dataset specify the solution data set to use in the evaluation data mphevalpoint model lt expr gt dataset lt dsettag gt lt dsettag gt is the tag ofa solution data set The default value is the current solution data set of the model e selection specify the domain selection for evaluation data mphevalpoint model lt expr gt selection lt seltag gt where lt seltag gt is the tag ofa selection node to use for the data evaluation lt seltag gt can also be a positive integer array that corresponds to the domain index list The default selection is all domains where the expression is defined If the evaluation point does not belong to the specified domain selection the output value is NaN e solnum specify the inner solution number for dat
226. y using interpolation curves and how to create geometry from image data 46 CHAPTER 3 BUILDING MODELS CREATING A GEOMETRY USING CURVE INTERPOLATION Use the interpolation spline feature to import a set of data points that describe a 2D geometry To create an interpolation spline feature enter model geom lt geomtag gt feature create lt ftag gt InterpolationCurve Then specify data points in a table model geom lt geomtag gt feature lt ftag gt set table lt data gt where lt data gt can either be a 2xN cell array or a 2xN array Control the type of geometry generated by the operation with the command model geom lt geomtag gt feature lt ftag gt set type type where type can either be solid to generate a solid object closed to generate a closed curve or open to generate an open curve Example Curve Interpolation Create a set of data points in MATLAB then use these to construct a 2D geometry Create data points that describe a circle sorted by the angle and remove some of the points phi 0 0 2 2 pi phi 1 3 6 7 10 20 21 25 28 32 p cos phi sin phi 2 Add some noise to the data points randn state 17 p pt0 02 randn size p 3 Create a 2D geometry with a square model ModelUtil create Model 4 Add a square geometry geom1 model geom create geomi 2 sqi geomi feature create sqi Square sqi set base center sqi set s

Download Pdf Manuals

image

Related Search

Related Contents

Samsung 사운드바 2.2채널  MyStar Extra® – Trainingsheft  Foster 2998 100 coffee maker  Safeware 59413 cable lock    25 Jet FourStroke - Brunswick Marine in EMEA Center  Benutzerhandbuch  July, 2006 Newsletter - MEDCOM Information Systems  Whirlpool LA6300XS User's Manual  User manual  

Copyright © All rights reserved.
Failed to retrieve file