• No results found

Type Inferencing and MATLAB to Modelica Translation

N/A
N/A
Protected

Academic year: 2021

Share "Type Inferencing and MATLAB to Modelica Translation"

Copied!
248
0
0

Loading.... (view fulltext now)

Full text

(1)

1

Institutionen för datavetenskap

Department of Computer and Information Science

Final Thesis

Type Inferencing and MATLAB to Modelica Translation

by

Mohammad Jahanzeb

LIU-IDA/LITH-EX-A--14/051-SE

2014-09-09

Linköpings universitet

581 83 Linköping

Linköpings universitet

(2)

2

Linköping University

Department of Computer and Information Science

Master's Thesis

Type Inferencing and MATLAB to Modelica Translation

by

Mohammad Jahanzeb

LIU-IDA/LITH-EX-A--14/051-SE

2014-09-09

Supervisor: Lena Buffoni

Department of Computer and Information Science

Examiner: Peter Fritzson

(3)

3

På svenska

Detta dokument hålls tillgängligt på Internet – eller dess framtida ersättare –

under en längre tid från publiceringsdatum under förutsättning att inga

extra-ordinära omständigheter uppstår.

Tillgång till dokumentet innebär tillstånd för var och en att läsa, ladda ner,

skriva ut enstaka kopior för enskilt bruk och att använda det oförändrat för

ickekommersiell forskning och för undervisning. Överföring av upphovsrätten vid

en senare tidpunkt kan inte upphäva detta tillstånd. All annan användning av

dokumentet kräver upphovsmannens medgivande. För att garantera äktheten,

säkerheten och tillgängligheten finns det lösningar av teknisk och administrativ art.

Upphovsmannens ideella rätt innefattar rätt att bli nämnd som upphovsman i den

omfattning som god sed kräver vid användning av dokumentet på ovan beskrivna

sätt samt skydd mot att dokumentet ändras eller presenteras i sådan form eller i

sådant sammanhang som är kränkande för upphovsmannens litterära eller

konstnärliga anseende eller egenart.

För ytterligare information om Linköping University Electronic Press se

förlagets hemsida

http://www.ep.liu.se/

In English

The publishers will keep this document online on the Internet - or its possible

replacement - for a considerable time from the date of publication barring

exceptional circumstances.

The online availability of the document implies a permanent permission for

anyone to read, to download, to print out single copies for your own use and to use

it unchanged for any non-commercial research and educational purpose.

Subsequent transfers of copyright cannot revoke this permission. All other uses of

the document are conditional on the consent of the copyright owner. The publisher

has taken technical and administrative measures to assure authenticity, security and

accessibility.

According to intellectual property law the author has the right to be mentioned

when his/her work is accessed as described above and to be protected against

infringement.

For additional information about the Linköping University Electronic Press and

its procedures for publication and for assurance of document integrity, please refer

to its WWW home page: http://www.ep.liu.se/

(4)

4

Abstract

Matlab is a proprietary, interactive, dynamically-typed language for technical computing. It is

widely used for prototyping algorithms and applications of scientific computations. Since it is a

dynamically typed language, the execution of programs has to be analyzed and interpreted which

results in lower computational performance. In order to increase the performance and integrate

with Modelica applications it is useful to be able to translate Matlab programs to statically typed

Modelica programs. This project presents the design and implementation of Matlab to Modelica

translator. The Lexical and Syntax analysis is done with the help of the OMCCp (OpenModelica

Compiler Compiler parser generator) tool which generates the Matlab AST, which is later used

by the translator for generating readable and reusable Modelica code.

(5)

5

Acknowledgements

I would like to express my deep gratitude to Professor Peter Fritzson and my supervisor Dr.

Olena Rogovchenko for their guidance, enthusiastic encouragement and useful critiques of this

research work. I would also like to thank my technical supervisor Mr. Arunkumar Palanisamy for

his advice and assistance in keeping my progress on schedule and helping me with the

difficulties I encountered.

I would also like to extend my thanks to IDA (Department of Computer and Information

Science) for offering its location and resources.

(6)

6

Table of Contents

Chapter 1 ... 10

Introduction ... 10

1.1 Introduction ... 10

1.2 Thesis Objective... 12

1.3 Intended Audience ... 12

1.4 Thesis Organization ... 12

Chapter 2 ... 14

Related Work ... 14

2.1 FALCON... 14

2.2 McFOR ... 14

2.3 Taming MATLAB ... 15

2.4 MATLAB Alternatives ... 15

2.4.1 GNU Octave... 15

2.4.2 FreeMat ... 16

2.4.3 Scilab... 16

Chapter 3 ... 18

Theoretical Background ... 18

3.1 What is MATLAB?... 18

3.2 Type System... 18

3.3 Matlab Language ... 19

3.4 Vector ... 19

Listing 3.4.b Column vector ... 19

3.5 Matrix ... 19

3.6 Matrix indexing ... 20

3.7 Colon operator (:) ... 20

3.8 Colon operator in a Matlab matrix ... 20

3.9 Matrix generators ... 21

3.10 Array operations... 21

3.10.1 Matrix arithmetic operations ... 21

3.10.1 Array arithmetic operations ... 22

3.11 Functions ... 22

3.11.1 Primary Function/Function ... 22

(7)

7

3.11.2 Sub-function ... 23

3.11.3 Anonymous Functions ... 24

3.12 Control Flow ... 24

3.13 Operators ... 24

3.13.1 Arithmetic operators ... 25

3.13.2 Relational operators ... 25

3.13.3 Logical operators ... 26

3.14 The OpenModelica Project ... 26

3.15 Modelica ... 27

3.16 MetaModelica ... 27

3.16.1 uniontype... 28

Listing 3.16.1 MetaModelica uniontype ... 28

3.16.2 match ... 28

3.16.3 list ... 29

Chapter 4 ... 30

Design and Implementation of a Matlab Scanner and Parser ... 30

4.1 Lexical Analysis: Scanner... 31

Listing 4.1: Lexical analysis ... 33

4.2 Flex ... 33

4.3 Syntax Analysis: Parser ... 36

4.4 GNU Bison... 37

4.5 OMCCp ... 39

4.6 Abstract Syntax of the MATLAB- AbsynMat.mo "MATLAB AST" ... 41

Chapter 5 ... 44

Design and Implementation of the Translator ... 44

5.1 Type Inference ... 46

Type Inference ... 47

5.1.1 Statement where the Right Hand Side is a constant ... 48

5.1.2 Statement where the Right Hand Side is Built-in function ... 49

5.1.3 Statement where the Right Hand Side is a computational expression and contains

arithmetic operator (array) ... 51

5.1.4 Statement where the Right Hand Side is a computational expression and contains an

arithmetic operator (scalar) ... 51

5.1.5 Statement where the Right Hand Side is a computational expression and contains a

relational operator ... 52

(8)

8

5.1.6 The Right Hand Side is not equal to the Left Hand Side ... 52

5.2 Translator ... 54

5.2.1 Primary Functions ... 54

5.2.2 Translation of function declaration statements ... 57

5.2.3 Identification and Translation of Local identifiers ... 58

5.2.4 Identification and Translation of constant identifiers ... 60

5.3 Translation of Function Body ... 63

5.3.1 Identification and Translation of Function Call ... 63

5.3.2 Identification and Translation of Anonymous function to sub-function ... 66

5.4 Translation of looping statements ... 68

5.5 Translation of if statements ... 69

5.6 Translation of Switch Statement ... 70

5.7 Sub-function ... 72

Chapter 6 ... 73

Testing and Performance Evaluation ... 73

6.1 Testing Lexer and Parser ... 73

6.2 Testing Translator ... 75

6.3 Performance ... 78

Chapter 7 ... 80

Conclusion and Future work ... 80

7.1 Conclusion ... 80

7.2 Supported Subset Features ... 80

7.3 Future work ... 81

7.3.1 Dimensions determination at Runtime ... 81

7.3.2 Variable type determination at Runtime ... 82

Chapter 8 ... 84

User Guide ... 84

8.1 Getting Started ... 84

8.2 Commands to Run the Code ... 84

References ... 86

Appendix A ... 89

Appendix B ... 92

Appendix C ... 105

(9)
(10)

10

Chapter 1

Introduction

1.1 Introduction

Matlab

1

is a high-performance interactive language for technical computing. It integrates

computation, visualization, and programming in an easy-to-use environment where problems and

solutions are expressed in familiar mathematical notation.[1]

It is a dynamically typed language

and thus it doesn't require any type declarations. A variable’s type is implicit from the semantics

of its operations and the type is allowed to dynamically change at runtime. These features

improves ease of use for prototyping and interactive use, but add heavy run-time overheads, such

as runtime type checking, array bounds checking and dynamic resizing, to its interpretive

execution. Therefore programs written in the Matlab often run slower than their counterparts

which are written in conventional statically typed programming languages.

The main goal of this work is the development of a translator that accepts Matlab programs as

input and generates Modelica code as output which is suitable for static compilation. Due to the

complexity of the Matlab language, a realistic goal is to develop a translator for a subset of

Matlab.

The translation task of Matlab to Modelica code mainly involves the front-end implementation of

the Matlab to Modelica compiler. The OMCC (OpenModelica Compiler Compiler) compiler

generation tool, which has been developed as a part of the OpenModelica project, can be used as

a parser and translator generator extended with advanced error handling facilities. The tool is

implemented in MetaModelica and integrated with the MetaModelica semantics specification

language based on operational semantics for generating executable compiler and interpreter

modules. The OMCCp part of the OMCC tool makes the implementation of the first two stages

of a compiler much easier. We have to write the lexer and parser rules for the Matlab language

and input them to the OMCCp to generate the appropriate lexer and parser modules in

MetaModelica. The generated parser builds the Abstract Syntax Tree (AST) for the Matlab

source code that is parsed. The Matlab AST is later used by the second phase of the

Matlab-to-Modelica translator which performs a series of internal transformations and finally generates the

1

(11)

11

Modelica-AST which is unparsed to readable Modelica code. Hence the implementation of

translator consists of two main parts. First the implementation of lexer & parser and second the

implementation of translator.

Figure 1.1: Overview of our Translator.

The overall goal of the translator is to take the Matlab programs m files as input and produce

output in Modelica language which is suitable for static compilation.

There exists a large body of computational algorithms which are programmed in the Matlab

language. They need to have an easy way of using and incorporating such algorithms within

Modelica models, as well as achieving improved performance, motivated the development of the

Matlab to Modelica translator in the OpenModelica project.[2]

Scanner Parser Translator Unparser OMCCp Matlab program .m files Tokens Matlab AST Modelica AST Modelica source code Lexer Generator Parser Generator

(12)

12

1.2 Thesis Objective

The objective of this master thesis project is to design and implement a translator for the

MATLAB language which not only enables the translation of the MATLAB programs to

Modelica code but also perform type inference to construct the type information. Moreover the

generated code is in readable & reusable form and maintain the original structure of code.

1.3 Intended Audience

The reader of this thesis report could be someone who has an interest in source to source

compiler specifically translating from dynamic to static language.

1.4 Thesis Organization

This thesis describes the design and implementation of Matlab to Modelica Translator. The rest

of the thesis is organized as follows. Chapter 2 covers the related work and alternatives of

Matlab Chapter 3 covers the theoretical background of Matlab, OpenModelica, Modelica and

MetaModelica language Chapter 4 covers the design and implementation of scanner and parse

Chapter 5 covers the design and implementation of translator Chapter 6 testing and performance

evaluation and finally Chapter 7 conclusion, supported subset features and future work.

(13)
(14)

14

Chapter 2

Related Work

In this chapter we discuss some previous related work in the area of compilers where the

attempts have been made for the performance improvement of Matlab programs. These projects

helped a lot in the development of our translator specially in the designing and implementing of

type inference algorithm. These research works include FALCON, McFor and MATLAB Tamer.

We also discuss some open source Matlab similar languages, which includes Octave, FreeMat

and Scilab.

2.1 FALCON

FALCON is a Matlab to Fortan 90 translator.

FALCON presented an excellent and simple algorithm to differentiate the Matlab functions from

an identifiers. [3] [4] We acquired a good idea from the algorithm presented for identification of

Matlab functions in FALCON project therefore we used similar approach in our translator and

discussed in detail about our approach in section 5.3.1 Identification and Translation of Function

Calls.

FALCON also presented the techniques for static inference method and dynamic inference

method to translate Matlab programs into Fortran 90. The approach they used for type

inferencing, is to process only one function at time and avoids the complexity of using Fortran to

simulate passing dynamically allocated arrays between functions. This is simple approach but the

problem with this approach is that, the generated code is less readable and thus difficult to reuse.

Since our goal is to generate readable and reusable code therefore we avoided this technique.

FALCON also inlines all the Matlab scripts and user-defined functions into single function thus

the generated Fortran code has only one function without any sub-functions.

2.2 McFOR

McFOR is a Matlab to Fortran 95 translator. McFor extracts information from the high-level

semantics of the Matlab programs to produce efficient, reusable and readable Fortran code. [5]

(15)

15

McFOR presented techniques for type inference which includes evaluation of basic types and

dimensions of an array variables and uses a value propagation analysis to precisely estimate the

sizes of arrays. We adopted a similar approach in our translator which is discussed in detail in

Section 5.1 Type Inference. [5]

McFOR generates readable Fortran code by translating the user-defined functions of the

MATLAB program into sub functions and keep the function declaration same as the original

MATLAB functions. The problem with McFOR is that it has an incomplete approach to the

builtin functions. Since built-in functions in the Matlab are well defined they play a very vital

role during type evaluation process. We tried to provide maximum support for built-in functions

specially functions for array generators, like zeros and ones. Further details about our approach is

in section 5.1.2 Statement where Right Hand Side is Built-in function.

2.3 Taming MATLAB

The Matlab tamer is an open source extensible object-oriented framework for generation of static

programs from dynamic Matlab programs implemented in Java. The Matlab Tamer supports a

large subset of Matlab. It builds a complete call graph, transforms every function into a reduced

intermediate representation, and provides typing information to aid the generation of static code.

[6]

2.4 MATLAB Alternatives

There are three alternatives. GUN Octave, FreeMat and Scilab.

2.4.1 GNU Octave

GNU Octave is a high-level language, primarily intended for numerical computations. [12] The

Octave language is almost similar to MATLAB and it is written in the C++ language where they

used polymorphism for type checking. This package was developed by John W. Eaton and

named after Octave Levenspiel, a professor at Oregon State University. GUN Octave also uses

BLAS (Basic Linear Algebra Subprograms), LAPACK (Linear Algebra Package) and other

Fortran packages. [7] The Octave language is quite similar to Matlab so that most programs are

easily portable. Since it is an open source language and the Octave grammar is available online

we got much help in writing the Matlab grammar for our translator, only we had to figure out the

(16)

16

differences between the Octave and Matlab languages. We identified the differences first and

made modification accordingly in the grammar file. We discuss this in detail in the section 4.3

Syntax Analysis.

2.4.2 FreeMat

FreeMat is a free environment for rapid engineering, scientific prototyping and data processing.

[13] It is an open source and similar to MATLAB and GUN Octave. FreeMat is available under

the GPL license. The supported operating systems for FreeMat include Windows, Linux, and

Mac.

The installation of FreeMat is user friendly. A Built-in editor is available for writing FreeMat

programs. The FreeMat system was developed by Samit Basu with the hope of constructing a

free numerical computational package that is Matlab compatible. Features for FreeMat include

eigenvalue and singular value decompositions, 2D/3D plotting, parallel processing with MPI,

handle-based graphics, function pointers, etc. [7]

2.4.3 Scilab

"Scilab is free and open source software for numerical computation providing a powerful

computing environment for engineering and scientific applications."[14] Scilab was written by

a group at INRIA, the French National Research Institution, in 1990.

The syntax is largely based on Matlab language and also supports hundreds of functions. The

supported functionalities include the following.

Maths & Simulation

For usual engineering and science applications including mathematical operations and data

analysis.

2-D & 3-D Visualization

Graphics functions to visualize, annotate and export data and many ways to create and customize

various types of plots and charts.

(17)

17

Optimization

Algorithms to solve constrained and unconstrained continuous and discrete optimization

problems.

Statistics

Tools to perform data analysis and modeling

Control System Design & Analysis

Standard algorithms and tools for control system study

Signal Processing

Visualize, analyze and filter signals in time and frequency domains.

Application Development

Increase Scilab native functionalities and manage data exchanges with external tools.

Xcos - Hybrid dynamic systems modeler and simulator

(18)

18

Chapter 3

Theoretical Background

In this chapter we present an overview of the Matlab language and cover the main differences

between the Matlab and Modelica languages. The next part present an overview of the

OpenModelica project including the Modelica and MetaModelica languages.

3.1 What is MATLAB?

The MATLAB (short for matrix laboratory) is a high-performance interactive language for

technical computing. It integrates computation, visualization, and programming in an easy-to-use

environment where problems and solutions are expressed in familiar mathematical notation. [1]

Typical uses include: Math and computation, Algorithm development, Modeling, Simulation,

and prototyping etc.

Some important features of the language are: Efficient matrix and vector computations, Easy

creation of scientific and engineering graphics, Application development, including graphical

user interface building and Object-oriented programming.

MATLAB was originally designed in the 1970s by Cleve Moler, then chairman of the computer

science department at the University of New Mexico. His main purpose was to give his students

access to LINPACK "LINear equations software PACKage" and EISPACK "Eigensystem

Package Subroutine Computing Facility" without learning Fortran. It almost immediately spread

to other universities and found a strong audience within the applied mathematics community. [8]

3.2 Type System

As we already discussed in the introduction part that Matlab is a dynamically typed language.

Variables are not declared while writing a program and the variable types are determined at the

runtime. Matlab automatically allocates the right amount of storage whenever it encounters a

new variable and if a variable changes it re-allocates memory.

It is also weakly typed language. Here the type of variables are not enforced. For example; we

can concatenate string "55" and the integer 6 to get "556" and then treat it as an integer without

stating any explicit conversions. Instead, conversions are made implicitly.

(19)

19

3.3 Matlab Language

Matlab is a high-level array language with control flow statements, functions, data structures,

input/output, and object-oriented programming features. [1]

Matlab is also one of the few languages in which each variable is a matrix.

A matrix is a

two-dimensional array consisting of m rows and n columns. Every value is a Matrix with some

number of dimensions, even scalar values are 1×1 matrices. Vectors are either 1×n or n×1

matrices and strings are just vectors of characters.

3.4 Vector

A vector in Matlab is a matrix with either one row or one column. The distinction between row

vectors and column vectors is important because Modelica declares such vectors differently. An

array of dimension 1 x n is called a row vector whereas an array of dimension m x 1 is called a

column vector. The elements of vectors are enclosed by square brackets and are separated by

spaces or by commas. Listing 3.4 shows the example of vector declaration in both languages.

Matlab - vec = [5,7,9,14,18]

Modelica - Integer[5] vec = array(5,7,9,14,18)

Listing 3.4. Vector

Column vectors are created in a similar way but we must separate the elements of column by

placing a semicolon (;). Listing 3.4.b shows the example of column vector in both languages.

Matlab - col_vec = [5;7;9;14;18]

Modelica - Integer[5,1] = [5;7;9;14;18]

Listing 3.4.b Column vector

3.5 Matrix

A matrix is a two-dimensional array consisting of m rows and n columns. The elements of matrix

are enclosed by square brackets same as vector and the elements in a row are separated with

commas or spaces. Since matrix contains more than one row thus semicolon (;) is used to

separate a rows. Listing 3.5. shows the example of matrix in both languages.

(20)

20

Matlab - matx = [1,2,3;4,5,6;7,8,9]

Modelica - Integer[3,3] matx = [1,2,3;4,5,6;7,8,9]

Listing 3.5. Matrix

Note: In Modelica, a column vector and a matrix have same declaration syntax.

3.6 Matrix indexing

Indexing into a matrix is a means of selecting a subset of elements from the matrix

.

The element

of row i and column j of the matrix Z is denoted by Z(i,j) therefore index Z(i,j) refers to the

element Zij of matrix Z. The first index refers the row number and the second index refers the

column number.

For example; A(1,3) is an element of first row and third column.

As shown above the Matlab uses parentheses () brackets for indexing however in Modelica

square brackets are used for matrix indexing.

For example; A[1,3]

3.7 Colon operator (:)

The colon operator is one of the most useful operator in the Matlab. It is used to create vectors,

subscript arrays, and specifying for iterations but often we deal with matrices or vectors that are

too large to enter one element at a time.

For example; If we want to enter a vector Z consisting of points (0,1,2,3,··· ,50). We can use the

command Z = 0:1:50;

The resulting row vector Z will have 51 elements.

3.8 Colon operator in a Matlab matrix

The colon operator can also be used to choose a certain row or column in a matrix.

For example; the statement Z(m:n,k:l) specifies rows m to n and column k to l. Subscript

expressions refer to portions of a matrix.

(21)

21

The colon operator can also be used to extract a sub-matrix from a matrix A.

A(:,2:3)

3.9 Matrix generators

Matlab provides builtin functions that generates elementary matrices such as the matrix of zeros

and the matrix of ones. The matrix zeros(m,n) returns an m-by-n matrix of zeros and the matrix

ones(m,n) returns an m-by-n matrix of ones.

For example; Z=ones(1,3)

The resulting row vector Z will have 3 elements of 1. The above statement is equivalent as

Z=[1,1,1]

X=zeros(2,3)

The resulting matrix X will have 2x3 dimensions. The above is equivalent to:

Z=[0 0 0;0 0 0]

Both zeros and ones functions are also used in Modelica for generation of matrices.

3.10 Array operations

There are two types of arithmetic operations.

Matrix arithmetic operations and Array arithmetic operations.

You can use these arithmetic operations to perform numeric computations, for example, adding

two numbers, raising the elements of an array to a given power, or multiplying two matrices.[8]

3.10.1 Matrix arithmetic operations

Matrix operations follow the rules of linear algebra and operate on whole matrices at once unless

an argument is a scalar. These include the matrix multiplication (*), and matrix division (\, /).

For example;

Matrix multiplication: C = A*B is the linear algebraic product of the matrices A and B. The

number of columns of A must equal the number of rows of B.

(22)

22

Matrix power: A^B is A to the power B, if B is a scalar. For other values of B, the calculation

involves eigenvalues and eigenvectors.

3.10.1 Array arithmetic operations

An array operations execute element by element operations and support multidimensional arrays.

The period character (

.

) distinguishes the array operations from the matrix operations. However,

since the matrix and array operations are the same for addition and subtraction, the character

pairs

.+

and

.-

are unnecessary.

Array operators;

.* Element-by-element multiplication

./ Element-by-element division

.^ Element-by-element exponentiation

Modelica uses same operators as the Matlab for array operations but the only difference is in

array addition and array subtraction. They must required period character. .+ and .- in the

Modelica language.

3.11 Functions

We discussed in detail the differences between Matlab and Modelica function in the section 5.2.1

Primary Function. Functions are an important feature of the Matlab. Besides builtin functions

Matlab also support primary functions, sub-functions and anonymous functions. All user built

functions are stored in M-files. Since these files have an extension .m thus these files are called

M-files and these files are input for our translator.

3.11.1 Primary Function/Function

A primary function allows us to create a user-defined function. The function definition states

how many inputs and outputs the function can accept and returned.

A function starts with the keyword

function

followed by output parameters, the function name

and the input parameters. The name of a function should be the same as the file name without

the .m extension.

(23)

23

In the listing 3.11.1 the function fnc should be placed in the file named as fnc which has an

extension .m. The given function calculates the mean and standard deviation of a vector and it

accepts a single input argument x, and returns the mean and stdev in the output argument. The

variables within the function body are local variables.

function [mean,stdev] = fnc(x)

n = length(x);

mean = sum(x)/n;

stdev = sqrt(sum((x-mean).^2/n));

end

Listing 3.11.1 Matlab function

3.11.2 Sub-function

If a M-file contains more than one function then the secondary function is called a sub-function.

A sub-function is visible only to the other functions in the same file. It is created by defining a

new function with the

function

keyword after the body of the preceding function or subfunction.

Example of primary and sub-function is given in the listing 3.11.2.

Listing 3.11.2. Primary function and sub-function

function [mean,stdev] = fnc(x)

n = length(x);

mean = avg(x,n);

stdev = sqrt(sum((x-avg(x,n)).^2)/n);

end

function mean = avg(x,n)

mean = sum(x)/n;

(24)

24

3.11.3 Anonymous Functions

An anonymous function is a function that is not stored in a program file but is associated with a

variable whose data type is

a

function_handle. Anonymous functions can accept inputs and

return outputs just as standard functions do. However they can contain only a single executable

statement. [8]

For example, create a handle to an anonymous function that finds the square of a number:

sqr = @(x) x.^2;

The variable

sqr

is a function handle. The

@

operator creates the handle, and the

parentheses

()

immediately after the

@

operator include the function input arguments. This

anonymous function accepts a single input

x

, and implicitly returns a single output, an array the

same size as

x

that contains the squared values.

Since Modelica does not support such functions, as an alternate we translate anonymous

functions to sub-functions in Modelica. We cover anonymous functions in detail in section 5.3.2

Identification and Translation of anonymous function to sub functions.

3.12 Control Flow

Matlab supports four different types of control flow structures. If statement, For loop, While loop

and Switch statement.

Modelica has almost similar control flow structure however it does not support the switch

statement so far, thus as an alternate we translate all switch statements to If Else statements in

Modelica. Note that MetaModelica has match expressions, which are generalized switch

expressions.

3.13 Operators

Matlab and Modelica operators are almost similar except the following:

Element wise addition: The translator converts the Matlab "+" to Modelica ".+"

Element wise and subtraction: The translator converts the Matlab "-" to Modelica ".-"

(25)

25

Logical operator AND: The translator converts the Matlab & to Modelica keyword "and"

Logical operator OR: The translator converts the Matlab | to Modelica keyword "or"

Logical operator NOT: The translator converts the Matlab ~ to Modelica keyword "not"

3.13.1 Arithmetic operators

Arithmeticd in MATLAB follows all the usual rules and uses the standard computer symbols

for its arithmetic operation signs.

plus - Plus

+

uplus - Unary plus

+

minus - Minus

-

uminus - Unary minus -

mtimes - Matrix multiply *

times - Array multiply

.*

mpower - Matrix power ^

power - Array power

.^

mldivide - Backslash or left matrix divide \

mrdivide - Slash or right matrix divide /

ldivide - Left array divide

.\

rdivide - Right array divide

./

3.13.2 Relational operators

eq - Equal

= =

ne - Not equal

~=

lt - Less than

<

(26)

26

le - Less than or equal

<=

ge - Greater than or equal

>=

Note especially the double = = for logical testing of equality. The single = is only used in

MATLAB for assignments.

3.13.3 Logical operators

and - Element-wise logical AND &

or - Element-wise logical OR |

not - Logical NOT

~

3.14 The OpenModelica Project

OpenModelica

2

is an open-source Modelica-based modeling and simulation environment

intended for industrial and academic usage. Its long-term development is supported by a

non-profit organization – the Open Source Modelica Consortium

3

(OSMC)

The goal with the OpenModelica effort is to create a comprehensive Open Source Modelica

modeling, compilation and simulation environment based on free software distributed in binary

and source code form for research, teaching, and industrial usage.

OpenModelica contains different tools that contribute with the design and construction of

simulation projects in OpenModelica. These tools are OMEdit, ModelicaML - UML-Modelica,

OMShell, OMNotebook, DrControl and DrModelica which are OMNote-book tutorial

documents, and Modelica Development Tooling (MDT).

2

OpenModelica: http://www.openmodelica.org

3

(27)

27

Figure 3.1: The architecture of the OpenModelica environment.

Detailed information about tools shown in above picture can be find in the given link;

https://openmodelica.org/index.php/openmodelicaworld/tools

3.15 Modelica

Modelica is an open standard and a statically strongly typed language. It is a non-proprietary,

object-oriented, equation based language to conveniently model complex physical systems

containing, e.g., mechanical, electrical, electronic, hydraulic, thermal, control, electric power or

process-oriented subcomponents. [9]

The design of the Modelica Language was started in the fall 1996 for standardization and

unification of multi-domain (multi-physics) modeling based on object oriented mathematical

modeling techniques by defining a model description language Modelica for modeling dynamic

behavior of engineering systems, intended to become a de facto standard.[9]

3.16 MetaModelica

MetaModelica is an extension of Modelica language which is used to model the semantics of the

Modelica language and other languages, and be able to express symbolic transformations of

models. MetaModelica has been developed as a part of OpenModelica project to provide a

platform for developing the OpenModelica compiler. MetaModelica adds new operators and

(28)

28

types to the Modelica language. We cover in this report the constructs uniontype, record, match

and list. [10]

3.16.1 uniontype

The uniontype is a construct that allows MetaModelica to declare types based on the union of 2

or more record types. It can be recursive and include other uniontypes. See the listing 3.16.1 as

an example of uniontype.

uniontype Exp

record INT

Integer integer ;

end INT;

record IDENT

String ident ;

end IDENT;

end Exp ;

Listing 3.16.1 MetaModelica uniontype

3.16.2 match

Match-expressions can be used either with the match or the mathcontinue keywords. The match

keyword refers that after a successful matching against a pattern in one of the case-branches no

more patterns will be matched. The matchcontinue keyword refers that even if there is a

successful match followed by a failed computation in the same case-branch, the matching will

continue with the subsequent case-branches. In our implementation we used only matchcontinue

expression. An example of the syntax for matchcontinue is presented in the listing 3.16.2.

matchcontinue s

case "one" then 1;

case "two" then 2;

case "three" then 3;

case _ then 0;

end matchcontinue;

(29)

29

3.16.3 list

The list operator is used to create linked lists of objects. The brackets are a constructor used to

define the list from the list elements. The operand ‘::’ is used to add items or to retrieve items

from a list. An example of the syntax for list is presented in listing 3.16.3.

list <Integer> z={1 ,2 ,3};

(30)

30

Chapter 4

Design and Implementation of a Matlab

Scanner and Parser

In this chapter we discuss the design and implementation of a Matlab scanner and parser. We

also present an overview of GNU Bison and Flex that have been used for parser generator.

The main tools that have been used in the implementation of a scanner and parser are GUN

Bison and Flex. GNU Bison is an automatic parser generator in the style of yacc whereas Flex

"Fast Lexical Analyzer" is an automatic scanner generator lex tool. [11]

Figure 4.1: Structure of Translator

Scanner Parser Translator Unparser OMCCp Matlab source code Tokens Matlab AST Modelica AST Modelica source code Lexer Generator Parser Generator

(31)

31

4.1 Lexical Analysis: Scanner

Lexical analysis or scanner is the process of converting a sequence of characters into a sequence

of tokens. Tokens are sequences of characters with a collective meaning. It identifies the special

tokens specified by a language making it more simple for the next phase i.e. syntax analysis of

the compiler. A program which performs lexical analysis or scanning is called a lexical analyzer

or lexer. A lexical analyzer or lexer is a program that runs a Finite Automata which recognizes a

valid language based on a regular expression. The tool which we have been using for lexical

analyzer is Flex "Fast Lexical Analyzer". The detail about Flex is described in next section.

The lexical analysis is our starting phase for translator. We wrote the lexical specification from

scratch and it supports the entire Matlab vocabulary including object oriented features. Before

implementing a lexer or scanner we had to identify the Matlab identifiers, digits, number,

keywords, arithmetic, relational & logical operators and special characters. Thus we identified;

 The Matlab identifier consists of a letter followed by zero or more underscores, letters or

digits.

IDENTIFIER

[a-zA-Z] [_a-zA-Z0-9]*

 The Matlab number can be Integer or can have decimal point and an exponent or both

decimal and exponent.

DIGIT

[0-9]

DIGITS

{DIGIT}+

EXPON

([DdEe][+-]?{DIGIT}+)

NUMBER

(({DIGIT}+\.?{DIGIT}*{EXPON}?)|(\.{DIGIT}+{EXPON}?)|(0[xX][0-9a-fA-F]+))

 Matlab uses i and j as a reserved characters for Imaginary units

Im

[iIjJ]

 Horizontal Spaces and Newlines

HSPACE

[ \t]

(32)

32

NEWLINE

((\n)|(\r)|(\r\n))

NEWLINES

{NEWLINE}+

 Matlab breaks a long statement by using contiguous sequence of three periods followed

by new line, carriage return or form feed character.

ELLIPSIS

\.\.\.

CONTINUATION {ELLIPSIS}[^\n\r\f]*{NEWLINE}?

 Comments starts with percent character '%' and continue until NEWLINE character or

end of the input.

COMMENT

\%[^\n\r\f]*{NEWLINE}?

 The scanner also identifies all keywords such as Function, End, While and If.

All arithmetic operators, logical operators, relational operators and special characters.

The complete lexerModelica.l file is available in appendix A.

The process of lexical analysis is shown in the listing 4.1. Lexer takes a source code as character

stream which in our case is the Matlab function and outputs a sequence of tokens. In the listing

4.1. the lexer recognized the tokens in the header line of the Matlab function keyword function,

an identifier perfect, assignment operator =, left parenthesis (, an identifier test_value and right

parenthesis ).

(33)

33

Listing 4.1: Lexical analysis

4.2 Flex

FLEX (Fast LEXical analyzer generator) is a tool for generating scanners, is a program which

recognize lexical patterns in text. It is also called a tokenizer. The Flex tool makes creating the

first stage of the compiler easier.

In order to construct a scanner, we only need to identify the vocabulary of the MATLAB

language and write a specification of patterns using regular expressions (e.g. DIGIT [0-9]) which

we already discussed in previous section.

A Flex file has three main sections, delimited by double percent sign "%%";

definitions //1st section %%

rules //2nd section %%

user code //3rd section "optional section"

Definition:- The definitions section contains declarations of simple name, definitions to simplify

the scanner specification, and declarations of start conditions.

(34)

34

Rules:- The rules section of the flex input contains a series of rules of the form;

pattern action

where the pattern must be unintended and the action must begin on the same line.

User Code:- The user code section is simply copied to lex.yy.c. It is used for companion routines

which call or are called by the scanner.

The flex program reads lexerModelica.l input file for a description of a scanner to generate. The

description is available in rules section in the form of pairs of regular expressions. In above

process we see that Flex generates a C source file named "lex.yy.c", which defines the function

yylex(). We require "lex.yy.c" file in order to generate lexer in MetaModelica languague. Which

we discuss in OMCCp section.

FLEX

lexerMatlab.yy.c

(35)

35

HSPACE [ \t] HSPACES {HSPACE}+ NEWLINE ((\n)|(\r)|(\r\n)) NEWLINES {NEWLINE}+ IDENTIFIER [a-zA-Z][_a-zA-Z0-9]* CONT (\.\.\.) Im [iIjJ] DIGIT [0-9] DIGITS {DIGIT}+ EXPON ([DdEe][+-]?{DIGIT}+) NUMBER (({DIGIT}+\.?{DIGIT}*{EXPON}?)|(\.{DIGIT}+{EXPON}?)|(0[xX][0-9a-fA-F]+)) %%

"function" return FUNCTION;

"end" return END;

"if" return IF;

"elseif" return ELSEIF;

"else" return ELSE;

"while" return WHILE;

"for" return FOR;

{DIGITS} return INTEGER;

{NUMBER} return NUMBER;

{NUMBER}{Im} return IMAG_NUM;

{IDENTIFIER} return IDENT;

{COMMENT} ; {HSPACES} ;

{NEWLINES} return NEWLINES; "\+" return ADD; "-" return SUB; "\*" return MUL; "\/" return DIV; "\^" return POW; ".*" return EMUL; "./" return EDIV; "\.\\" return ELEFTDIV; "\.^" return EPOW; "\<" return EXPR_LT; ">" return EXPR_GT; "\<=" return EXPR_LE; ">=" return EXPR_GE; "==" return EXPR_EQ; "~=" return EXPR_NE; %%

The content of the lexerModelica.l file is above which contains all the keywords and tokens of

the MATLAB language. The complete lexerModelica.l file is available in appendix A.

Definition

(36)

36

4.3 Syntax Analysis: Parser

The second phase of the translator is Syntax Analysis. In the previous phase "lexical analysis"

the input is split into tokens and which are provided as input to syntax analysis "parsing" to

recombine these tokens to form a syntax tree that reflects the structure of the text. The leaves of

the syntax tree are the tokens.

Since the Matlab is not a free software thus we couldn't find a Matlab grammar.Writing the

whole grammar from scratch is a tedious task. However, we managed to find an alternative of the

Matlab which is GNU octave.

GNU Octave is a high-level interpreted language, primarily intended for numerical

computations.[12] The GNU Octave language is quite similar to Matlab but still the grammar of

Octave is not fully supported therefore we identified the dissimilarities between both languages

first and made changes accordingly in our Matlab grammar file. Currently the Matlab translator

parser supports for the entire Matlab syntax including classes.

Sample grammar rules for the Matlab function is given below. The complete parserModelica.y

file is available in Appendix B section.

 Matlab support function with or without output.

function_list: function1 {}

% without output %

| return_list EQ function1 {} % output handles in return list %

 Function name as identifier

fcn_name

: identifier {}

 Function can be with or without parameters.

 opt_sep "operator separator": Statements in the Matlab are separated from each

other by delimiters. Delimiters can be semicolon ';', can be comma ','.

function1

: fcn_name param_list opt_sep opt_list function_end {}

% with parameter %

(37)

37

 Function can be ended with or without an End keyword, since its optional in

Matlab.

function_end: {} /* empty */ % without End keyword %

| END {} % with End keyword %

4.4 GNU Bison

GNU Bison is free software and is available under the GNU General Public License. GNU

Bison is a general purpose parser generator that converts a grammar description for an LALR(1)

context free grammar into a C program to parse that grammar. Bison is a bottom up parser

generator. The parser accepts strings belonging to the language generated by the grammar and

rejects all other strings. The grammar can be ambiguous and precedence is used to resolved the

resulting conflicts.

A Bison grammar file has four main sections, shown in the listing 4.4. with the appropriate

delimiters:

%{

Prologue // 1st section

%}

Bison declarations //2nd section

%%

Grammar rules //3rd section

%%

Epilogue //4th section "optional section"

Listing 4.4: Bison Grammar

Prologue:- The prologue section usually contains #include lines, macro definitions and C

declarations.

Bison Declaration:- Declarations related to bison or yacc comes under this section.

Grammar rules:- This section contain actual grammar rules and their associated semantic actions.

Epilogue:- Additional C code that commonly corresponds to functions invoked from the

semantic actions.

Bison

parserMatlab

.tab.c

parserMatlab.y

(38)

38

Bison receives as an input a parserModelica.y file with the grammar rules. The output of the

process is a parser written in C that communicates with a lexer. We require the

"parserModelica.tab.c" file in order to generate a parser in the MetaModelica language. This we

discuss in the OMCCp section.

%{

import AbsynMat;

/* Type Declarations */

type AstTree = AbsynMat.Start; type Token = Types.Token;

constant list<String> lstSemValue3 = {}; constant list<String> lstSemValue = {

"error", "$undefined", "FUNCTION", "END", "IF", "ELSEIF", "ELSE", "WHILE", "FOR", "SWITCH", "CASE", "OTHERWISE", "GLOBAL", "BREAK", "CONTINUE",

"RETURN", "CLASSDEF", "PROPERTIES", "simple_list1", "list", "list1", "opt_list", "input1"}; %} %token FUNCTION %token END %token IF %token ELSEIF %token ELSE %token WHILE %token FOR %token SWITCH %% /* Looping */

loop_command: WHILE stash_comment expression opt_sep opt_list END

{ $$[Command] = AbsynMat.WHILE_COMMAND ($3[Expression], SOME($4[Separator]), $5[Statements], SOME($2[Mat_Comment])); }

| FOR stash_comment assign_lhs EQ expression opt_sep opt_list END

{ $$[Command] = AbsynMat.FOR_COMMAND ($3[Arguments],

$5[Expression], SOME($6[Separator]), $7[Statements], SOME($2[Mat_Comment])); }

/* Function file */

function_file: FUNCTION function_list opt_sep opt_list

{ $$[Start] = AbsynMat.START($2[User_Function], $3[Separator], $4[Statements]); } /* Function definition */ $1[User_Function]::$3[User_Functions]; }

Prologue

Bison Declaration

Grammer Rules

(39)

39

function_list: function1 { $$[User_Function] = AbsynMat.FINISH_FUNCTION

({},$1[User_Function]); } %%

Regarding the content of parserMatlab.y file, the complete file is available in Appendix B

section.

This file includes the Matlab tokens in the Bison declaration section and Grammar rules for the

Matlab language. The rules are written in the form of context free grammar. The lower-case

letters denote non-terminals and upper-case letters denote terminals. Bison performs parsing

according to rules one at a time and if a rule succeed the corresponding AST part is created.

4.5 OMCCp

The OpenModelica Compiler-Compiler parser generator (OMCCp) is the tool that generates a

Lexer and Parser in the MetaModelica language based on the grammar file. OMCCp is

composed of two packages, the Lexer Generator and the Parser Generator.

(40)

40

Figure 4.2: Structure of OMCCp

The OMCCp tool is used for the generation of Lexers and Parsers in MetaModelica which is then

compiled with OpenModelica compiler (OMC). The Parser and Lexer Generator are based on the

generated files by FLEX and BISON from the grammar files lexerMatlab.l and parserMatlab.y.

The two packages LexerGenerator.mo and ParserGenerator.mo are responsible for the generation

of the complete Compiler Compiler in MetaModelica code.

 Lexer.mo:- The main purpose of this file is to load the source code file and

recognize all the tokens described by the grammar and returns as an output to the

parser either a list of tokens or an error if no tokens were found.

 LexerGenerator.mo:- The Lexer Generator for OMCCp is implemented in the file

LexerGenerator.mo. It receives a FLEX generated lexerMatlab.c file as input. The

FLEX generated file contains the required information to be used by the Lexer.mo

file. There are in total three files generated by the Lexer Generator.

LexerModelica.mo, LexTableModelica.mo and LexerCodeModelica.mo.

Parser.mo:- The main purpose of this module is to efficiently convert a list of

tokens received by the Lexer into the Matlab AST "Abstract Syntax Tree"

described in the Absyn.mo file. This converted Matlab AST is required as Input

by our translator to preform translation of Matlab AST to Modelica AST which

we will discuss in next chapter "Implementation and Design of Translator".

 ParserGenerator.mo:- The Parser Generator for OMCCp is implemented in the

file ParserGenerator.mo. It receives Bison generated parserMatlab.c file as a

input. The Bison generated file contains the required information to be used by

Parser.mo file. There are four files generated by the Parser Generator.

ParseModelica.mo, ParseTableModelica.mo, ParseCodeModelica.mo and

TokenModelica.mo

 TokenModelica.mo:- This file is the link between the lexer and the parser and it is

used by both to identify the tokens.

(41)

41

4.6 Abstract Syntax of the MATLAB- AbsynMat.mo "MATLAB AST"

Abstract Syntax Tree:- The representation of Source Code as a tree of nodes, representing

constants or variables (leaves) and operators or statements (inner nodes) is called an AST.

An AST is the output of a parser thus It is also known as parse tree.

uniontype Start record START User_Function usr_fun; Separator sep; list<Statement> stmt_lst; end START; end Start;

Listing 4.6: AST

In the listing 4.6 the uniontype “Start” is the main AST construct of the Matlab. The Matlab

language always start from the function and can be separated by operator, if file contains more

than one function. The first function is called primary function and the rests are called secondary

functions. Thus our record "START" contains three uniontypes. The first uniontype is the

User_Function which handles the Matlab function, which could be single or primary function

then Separator uniontype, in case file contains more than one function thus we separate more

functions by separator and finally Statement uniontype which is list of statements. This list

contains secondary function.

function_file: FUNCTION function_list opt_sep opt_list

{ $$[Start] = AbsynMat.START($2[User_Function], $3[Separator], $4[Statements]); }

The above code is taken from parserMatlab.y which is relevant to the above Start AST

construct. The first line is the grammar rule where the letters in small are terminals and letters in

large are non terminals or tokens. In second line "AbsynMat" is the file which contains the entire

Matlab AST, here the letters in the capital are the record types and letters in normal are the

uniontypes. If above grammar rule parsed then it creates the AST accordingly define in

AbsynMat.mo file. The complete Matlab-AST constructs refer the Appendix C section.

(42)

42

uniontype User_Function

// Begin defining a function.

record START_FUNCTION Ident fname;

list<Parameter> prm;

Option<Separator> sep;

list<Statement> stmt_lst;

Statement stmt_2nd;

end START_FUNCTION;

// Finish defining a function.

record FINISH_FUNCTION list<Decl_Elt> ret;

User_Function usr;

end FINISH_FUNCTION;

end User_Function;

Listing 4.6.b: AST

In the listing 4.6.b uniontype “User_Function” is the AST for the Matlab function. This

uniontype contains two records. The first is called START_FUNCTION and the second is called

FINISH_FUNCTION.

The first record is composed of Ident, Parameter list, Optional separator, Statement list and

finally Statement. The START_FUNCTION record handles function name, input parameters of

the function which can be zero "empty/{}" or more, separator operator such as semi colon, colon,

new line etc and then function body which is list of statements and finally function ends on

Statement uniontype with the keyword end.

function1

: fcn_name param_list opt_sep opt_list function_end

{

$$[User_Function]

=

AbsynMat.START_FUNCTION

($1[Ident],$2[Parameters],

SOME($3[Separator]), $4[Statements], $5[Statement]); }

| fcn_name opt_sep opt_list function_end

{ $$[User_Function] = AbsynMat.START_FUNCTION ($1[Ident],{}, SOME($2[Separator]),

$3[Statements], $4[Statement]); }

Second record composed of Decl_Elt list uniontype and recursive User_Function

uniontype. The Decl_Elt list uniontype handles the output of the function which could be zero

(43)

43

"empty/{}" or more. We used recursive User_Function uiontype because it recalls itself again for

constructing the further part of the function, which is the START_FUNCTION record.

function_list: function1

{ $$[User_Function] = AbsynMat.FINISH_FUNCTION ({},$1[User_Function]); }

| return_list EQ function1

(44)

44

Chapter 5

Design and Implementation of the

Translator

This chapter covers the design and implementation of the translator. We first discuss our type

inference algorithm and later the actual translator.

The main challenge of the MATLAB to Modelica translator is to perform inference on the input

programs to determine each variable’s type and size and transform them into compatible forms

for easily and effectively generating Modelica code.

Our translator is built around the following requirements:

1. The translator supports a subset of the MATLAB features that are commonly used for

scientific computations: All supported subset features are available in section 7.2 Supported

Subset Features..

2. The translator is designed to be used for translating existing MATLAB programs into

Modelica code, so we assumes that the input MATLAB programs are syntactically and

semantically correct though translator still detected lexical errors during the process of the

lexical analysis and syntax error while parsing.

Matlab AST

Modelica AST

The translator performs type inference before transformation of code and takes the Matlab AST

as input and output the Modelica AST. In order to compile the generated code using OMC we

(45)

45

have to accurately analyze the Matlab code, evaluate proper types including size of arrays and

map to the AST of Modelica. Both languages are very different in nature and Matlab has

comparatively simple syntax with no variable declaration. These features make Matlab very easy

to write code in but associated with the simple syntax there is much more complex semantics

that relies on the actual types of the operands and variables thus we identify the main differences

first.

 Identification of variable identifiers and declaration with proper data type.

 Identification of array identifiers and declaration with proper size and data type.

 Identification of local identifiers and declaration under the protected section along

with data type.

 Identification of constant identifiers.

 Identification of function calls.

 Identification of index operation.

 Identification of built-in functions.

 Identification of Anonymous functions.

(46)

46

Figure 5.1: Structure of the Translator

5.1 Type Inference

We have adopted the McFOR "A Matlab To Fortran95 Compiler" approach for evaluating the

types in our translator. It starts by analyzing each assignment statement on the right hand side

(RHS) of the expression and assign types. [16]. The type inference process starts by analyzing

each assignment statement in the AST, the translator saves all the assignment statements in a

single list with a delimiter string. Delimiter string i.e. "nstmt" assists translator while splitting the

list to identify the end of previous and start of new statement.

For example; if the Matlab function contains the assignment statements below:

radius = 10.5; num_boxes = 4; box_length = (2.0*radius)/num_boxes; Scanner Parser Translator Unparser OMCCp Matlab source code Tokens Matlab AST Modelica AST Modelica source code Lexer Generator Parser Generator

(47)

47

After traversing the entire AST, we have a list of given strings but here each identifier contains

three additional strings which we appended during the process of traversing. The detail about

these strings are explained in the next section.

{Scalar, 1, 1, radius, Real, nstmt, Scalar, 1, 1, num_boxes, Integer, nstmt, Scalar, 1, 1,

box_length, Unknown, Scalar, 1, 1, rconstant ,Real, MUL, Scalar, 1, 1, radius, Unknown, DIV,

Scalar, 1, 1, num_boxes, Unknown}

Once the translator collected all the assignment statements from the provided Matlab function we

start the process of evaluating the types by examining each assignment statement but first we

split each statement with the help of delimiter sign i.e. "nstmt". After splitting the whole list then

the translator examine the Right Hand Side of each statement on the basis on the following

sources.

(48)

48

5.1.1 Statement where the Right Hand Side is a constant

We found that constant values are very precise sources for accessing data types. They provide a

good source to start the process of type inference. During the process of analyzing, we append

three extra strings to each identifier. The first represents either the identifier is a Scalar or an

Array and the second & third represents the dimensions of an array. How does the translator

knows which string to append depends on the right hand side of the constant identifier. The

translator examine the right hand side of a constant statement to assess either the identifier on the

left hand side is a scalar or an array. Since the scalar identifier has 1 dimension we appended "1"

in the case of an array the translator count the elements first and then append the dimension.

For instance if the translator finds an assignment statement where the right hand side is a

constant (e.g.) temp = 10 we append the string scalar and dimension 1,1 with a temp identifier.

Since 10 is an integer value we assess the type Integer.

temp = 10

i_lst3 = listAppend({"Scalar"},{"1"},{"1"});

Scalar, 1,1, temp, Integer

- right hand side contains a real value.

temp = 10.5

i_lst3 = listAppend({"Scalar"},{"1"},{"1"});

Scalar, 1,1, temp, Real

- right hand side contains a vector or row vector

temp = [1,2,3,4] // 1 x 4

i_lst3 = listAppend({"vector"},{"1"},{dim});

vector, 1,4, temp, Integer- right hand side contains a column vector

temp = [1;2;3;4] // 4 x 1

i_lst3 = listAppend({"column_vector"},{dim},{"1"});

column_vector, 4,1, temp, Integer

References

Related documents

Att anv¨anda linspace ¨ar det effektivaste s¨attet vid grafritning d˚ a vi har ett intervall vi ¨ar intressede av (start- och slutv¨arde) och vill bara ha tillr¨ackligt m˚

Nu skall vi bilda en matris S som skall h˚ alla ordning p˚ a vilka h¨ornpunkter som ¨ar h¨orn p˚ a de olika sidorna i tetraedern.... P˚ a s˚ a s¨att ser vi vilka sidor vi inte

&gt;&gt; for i=1:5, for j=1:5, A(i,j) = sin(i/10)*sin(j/10), end, end Om man skriver end; end; d¨aremot, s˚a f˚ar man samma resultat, dvs semikolon efter end har ingen verkan

Påpekande: för att man ska veta vilken metod man ska använda och för att man ska kunna tolka resultaten från programmen krävs kunskaper i matematik och numerisk analys.. Per

Vektorer används ofta för att spara serier av värden, t.ex. en serie

Vill man att funktionen skall klara elementvisa kalkyler (som i de flesta fall i denna kurs) måste man använda ”punk- terade operationer” (dvs. Om en viss anonym funktion saknar

I Kan använda kommandot fzero för att hitta nollställen till funktioner...

The moore2SYNextStatef func- tion block has a default function that sums the three arguments to calcu- late the next value while the moore2SYOutf function block has a default