text:
Adiabatic perturbation theory in quantum dynamics.(English)Zbl 1053.81003

Lecture Notes in Mathematics 1821. Berlin: Springer (ISBN 3-540-40723-5/pbk). vi, 236 p. (2003).
This book addresses the important issue of scale separation in complex systems and other situations in natural sciences. Sometimes, scales are well separated and it is not difficult to derive simple laws for some or all of the slow variables in terms of the fast ones. But even before that, the precise meaning of slow and fast variables must be clarified, and indeed may differ widely in different systems. As explained by the author, a spinning top constitutes a simple example for the kind of situations considered in the monograph while it spins at high frequency, its rotation axis precesses much slower. The orientation of the rotation axis is the slower degree of freedom in this example, while the angle of rotation with respect to the axis is the fast one. In the case of the Earth, it turns once a day while it precesses only once in 25700 years.
In the monograph, quantum mechanical systems which display such a scale separation are considered, the prototype example being molecules, i.e., systems consisting of two types of particles with very different masses (generically, electrons are lighter than nuclei by a factor of over one thousand, so that they move at least 50 times faster). Fast degrees of freedom become slaved by slow ones, which evolve autonomously, a phenomenon called adiabatic decoupling. As explained in the book, this is common to a large variety of physical systems, for which similar mathematical methods can be applied. The fast scale is the quantum mechanical time scale, involving Planck-s constant $$\hbar$$. The abstract mathematical question involved is the $$\hbar \to 0$$ limit of Schrödinger’s equation with a special type of Hamiltonian. In many interesting situations the complexity of the full system makes a numerical treatment of this equation impossible. Even a qualitative understanding of the dynamics cannot be based on the equation of motion alone, and one is led to find more simple effective equations of motion that yield reliable approximate solutions when $$\hbar \to 0$$.
The monograph reviews an approach to adiabatic perturbation theory in quantum dynamics which goal isto find asymptotic solutions to the mentioned initial value problem, as solutions of an effective Schrödinger equation for the slow degrees of freedom alone. An insight of the approach consists in a clear separation of the adiabatic limit from the semiclassical one: it turns out that adiabatic decoupling is a necessary condition for semiclassical behavior of the slow degrees of freedom. Related with this is the emphasis on dealing with effective equations of motion, as opposed, e.g., to the direct construction of approximate solutions to the Schrödinger equation based on the WKB Ansatz or semiclassical wave packets.
After an introductory chapter (Chapter 1), the monograph contains three main parts. In Chapter 2 first order adiabatic theory for perturbations of fibered Hamiltonians is discussed. This is done with the mathematical tools of a standard course on unbounded self-adjoint operators on a Hilbert space. In Chapter 3 the general problem is considered and a theory is developed which allows for approximations to an arbitrary order in powers of $$\hbar$$. Chapters 4 and 5 are devoted to applications and extensions of the general scheme, termed by the author adiabatic perturbation theory. The main mathematical tool in Chapters 3-5 are pseudodifferential operators with operator valued symbols. While all these chapters deal with adiabatic decoupling in the presence of a spectral gap for the Hamiltonian, Chapter 6 is concerned with adiabatic theory without a spectral gap. The author leaves outside the scope of the monograph a comparison of the quantum mechanical results with those of classical adiabatic theory, which is a well studied subject on its own. This would be highly interesting, and could serve as a check or a guide, in view of the novelty of the results discussed here. In an Appendix some necessary definitions and results are collected, together with references to the literature.

MSC:

 81-02 Research exposition (monographs, survey articles) pertaining to quantum theory 81Q15 Perturbation theories for operators and differential equations in quantum theory 47G30 Pseudodifferential operators 35Q40 PDEs in connection with quantum mechanics 37N20 Dynamical systems in other branches of physics (quantum mechanics, general relativity, laser physics)
Full Text:


text:
# Use of Script-size and Script-script-size glyphs

In the answers to this question, I learned that OpenType Math fonts like Cambria and Latin Modern Math contain script-size and script-script-size characters, with different optical scaling. In my documents, I see that the script-script-size ones (with .sts names) are being used for subscripts. This is surprising -- I was expecting that the script-size ones would be used (the ones with .st names). The effect is not very noticeable, because the vertical sizes of the subscript characters are as I would expect -- roughly 7 pt for a document that uses 10 pt as the basic text size.

In short, I was expecting to get the result on the right, and I'm getting the result on the left (in both displayed and in-line math). Is this to be expected? If it is, then what are the script-size glyphs used for ??

Edit
This seems to be related to the use of Unicode-Math.

% Compile using XeLateX
\documentclass{article}
\usepackage{unicode-math}
\begin{document}
$x_2 = 2$
\end{document}

Removing the third line of code gives the result I'd expect -- the "two.st" glyph is used.

Reported as a bug on github.

• I am getting the same error and I would call it as such. Please report this here: github.com/wspr/unicode-math/issues?q=is%3Aopen+is%3Aissue Chapter 4.2 of the documentation says that those fonts should get selected by default. Off topic: Please do not use ! – LaRiFaRi Jan 6 '15 at 8:28
• I don't understand this stuff at all, so I don't know if it's an error or not. I somewhat like it, actually. I'll report it as a bug if that's the consensus. Let's wait a while, first, though. – bubba Jan 6 '15 at 9:41

Ah, thanks very much for spotting this! The reason this occurs is two-fold.

Firstly, when loading a maths font, unicode-math queries it to establish the sizes it should define for script and scriptscript sizes. After doing this, it needs to re-load the font with these new sizes, and that wasn't happening. (I don't know if this was actually a problem in practise, but it's been fixed.)

Secondly, and more importantly, TeX is notorious for its mathematics ability, and after reading in the appropriate values it needed to do some rescaling for the main font size. This was being done poorly, resulting in a value of 6.99997pt instead of 7pt. Because the font was defined to switch from script to scriptscript below 7pt, this triggered the result you show above.

I've now re-implemented this using expl3's floating point mathematics engine; for those curious this has changed

\cs_set:Nn \@@_fontdimen_to_percent:nn
{ \strip@pt\dimexpr\fontdimen#1#2*65536/100\relax }
\cs_set:Nn \@@_fontdimen_to_scale:nn
{ \@@_fontdimen_to_percent:nn {#1} {#2} \dimexpr \f@size pt\relax }

to

\cs_new:Nn \@@_fontdimen_to_percent:nn
{ \fp_eval:n { \strip@pt\fontdimen#1#2 * 65536 / 100 } }
\cs_new:Nn \@@_fontdimen_to_scale:nn
{ \fp_eval:n {\@@_fontdimen_to_percent:nn {#1} {#2} * \f@size } pt }

Now! Something I hope doesn't become a problem: this new method produces a size of 7.01236pt (for Latin Modern Math, TL2015). I would have expected 7pt, so I hope there isn't something else in here that might trip us up later.

Another way to solve this problem would be to avoid defining the font change at the boundaries, but rather in their middles. E.g. if the font says that SS-size is 5pt and S-size is 7pt for a 10pt font, it would kind of make more sense to define the font as something like:

6pt and below : script script size font
6pt - 8.5pt   : script size font
8.5pt and up  : regular size font

I might investigate this solution instead if the issue you've raised re-occurs in similar form in the future.

• Thanks for the fix. I make my living doing floating-point computations, and I'd say that using any number close to 7 as the "test" value is asking for trouble. Your suggestion in "another way " sound much safer, to me. – bubba Jul 31 '15 at 4:39
• @bubba — the main reason I haven't implemented this straight away (besides laziness) is that I'm aware there are larger problems surrounding the way that the script sizes are calculated; namely, that these are frozen for the text size, and so writing \Huge$x^a_b$ will have a and b in "regular size glyphs" but scaled up. I'm not sure if this is appropriate or not, but deserves finer consideration… – Will Robertson Jul 31 '15 at 7:03

format: plain


text:
# Questions tagged [complexity-classes]

Computational complexity classes and their relations

563 questions
Filter by
Sorted by
Tagged with
34 views

### Is there a $BPP$ like class stronger than $P$ and weaker than $BPP$?

$P/poly$ is a class of problems solvable in $P$ for every input length $n$ provided we have an advice string of length $poly(n)$ that depends only on $n$. $BPP$ is class of problems solvable with ...
45 views

### On the classes $E$, $DTIME$ and $NTIME$? [closed]

For every $c>0$ is there a $c'$ such that $DTIME(n^c)^E\subseteq DTIME(2^{n^{c'}})$ hold and vice versa for every $d'>0$ is there a $d$ such that $DTIME(2^{n^{d'}})\subseteq DTIME(n^d)^E$ hold? ...
92 views
+100

### Diagonalization arguments for QMA type proof systems

Diagonalization is a very common technique to find oracle separations. For example, it can be used to separate $\cal{P}$ and $\cal{NP}$, with the essential idea being that of constructing an oracle in ...
91 views

### Complexity of two promise graph coloring problems [closed]

I. Consider the problem 'Given a chromatic number $k$ graph on $n$ vertices then for all coloring with $k$ colors is there always a color with at least $m$ vertices?'. What is the known complexity ...
100 views

### Why can MIP be restricted to just two provers?

In several places I see it referred to that the MIP class can be assumed to be two interactive provers that don't communicate with each other, rather than any polynomial number of provers. Why are ...
224 views

### Is there an assumption that implies $P=ZPP$ which is not known to imply $P=BPP$?

There are assumptions that are known to imply that $P = BPP$. For example, if there exists a function in $E = DTIME(2^{O(n)})$ that has circuit complexity $2^{\Omega(n)}$, then $P = BPP$ [1]. Clearly, ...
143 views

### Complexity class of efficient streaming algorithms

Consider the class of problems $\mathsf{StreamL}$ which can be solved in logarithmic space reading the input in a single pass from left to right. In other words: $L \in \mathsf{StreamL}$ if there ...
109 views

### Is there an analogue of QMA where Merlin gives Arthur unitaries rather than states?

$\def\braket#1#2{\langle#1|#2\rangle}\def\bra#1{\langle#1|}\def\ket#1{|#1\rangle}$Is there an analogue to $\mathsf{QMA}$ where Merlin provides to Arthur single-use access to a unitary operator $U$? By ...
268 views

### The theoretical complexity of Go - The state of the art

What are the latest advances in theoretical complexity of Go? I know some early works about the complexity of Go: "Go is polynomial-space hard" proved that Go is PSPACE-hard. "Ladders are PSPACE-...
96 views

### Is PP invariant under changing its cut-off from 1/2 to another number?

Suppose I have a fixed family of quantum circuits $\{C_i\}$ for which determining whether the maximum output acceptance probabilities are $p\geq 1/2$ or $p< 1/2$ is PP-hard. Now suppose I have the ...
108 views

18 views

### Sorting using comparisons that are not simple mappings of simple comparisons

The Python language has a sort(x) function that sorts a list based on the intrinsic comparison operator associated with the type of the elements of its input list x. One can also provide a cmp ...
166 views

### Problem in deterministic time $n^p$ and not lower

I'm looking for any language $L$ candiate to be in $DTIME(n^p) -DTIME(n^{p-1})$ (it takes at least $n^{p-1}$ steps to determine if an input is in L with a 2-tape $TM$, but L is polynomially solvable). ...
155 views

### Containment problem of an acyclic NFA in an NFA

Let $A$ and $B$ be NFAs, such that $A$ is acyclic. In the general case, deciding whether $L(A)\subseteq L(B)$ is $PSPACE$-hard. However, since $A$ is acyclic, we know that for every $w \in L(A)$, it ...
46 views

### Randomized Reduction for Maximization Problem

I have two maximization problems $P_1$ and $P_2$ where the decision version $L_1 = \{(x, t) : \operatorname{Val}_1(x)\ge t\}$ of $P_1$ is $\mathsf{NP}$-complete. Let $f:P_1\to P_2$ be a randomized ...
87 views

75 views

### Are there common names for the subtiers of PTIME?

We all know P, or PTIME, I think, as a common name for the class of polynomial-time problems. Are there common names for the first few levels inside P; that is, for constant-time, linear-time, ...
164 views

### On complexity class $\mathsf{\Pi_2 L}$

I suggest the following definition of $\mathsf{\Pi_2 L}$ (similarly to the certificate definition of $\mathsf{NL}$): A language $L$ belongs to $\mathsf{\Pi_2 L}$ iff there exists a deterministic ...
188 views

I have found the following question at openproblemgarden.org: The problem concerns the extension of Monadic Second Order Logic (over a binary relation representing the edge relation) with the ...
164 views

### A canonical complete problem for EXP and NEXP in terms of formulae

3SAT is a complete problem for NP. TQBF is a complete problem for PSPACE. Is there direct way to define canonical complete problems for EXP and NEXP in terms of boolean formulae? I have only seen ...
308 views

110 views

### When is a problem specified on a TM contained in non-uniform classes such as P/poly? [closed]

In this paper by Gottesman and Irani: https://arxiv.org/abs/0905.2419 , they prove NEXP-hardness of tiling an $N\times N$ grid. They do so by encoding a TM in the tiles making up the grid. However, ...
245 views

### Example problem that is not in $2^{o(n)}$ but could be solved in $O(2^{cn})$ for any $c > 0$ (suggested by wording of ETH)

In the wikipedia article on Time Complexity it is written that: The exponential time hypothesis (ETH) is that 3SAT, the satisfiability problem of Boolean formulas in conjunctive normal form with, ...
It has been known since the early 70's that ${\bf NP}$ and ${\bf E}=DTIME(2^{O(n)})$ are not equal (because ${\bf E}$ is not closed under polynomial-time many-one reductions, in contrast to ${\bf NP}$...


text:
# How to use data generator for regression keras?

I am using the Keras data generator to load data from a directory. I am basically dealing with a regression i.e there is a numerical value for each of my images in the range [-1 1]. I am using the following code to load images from the directory:

df=pd.DataFrame(columns=['Image','Steer'])
df['Image']=filenames
df['Steer']=steer

from sklearn.model_selection import train_test_split
train_x,test_x,train_y,test_y=train_test_split(df['Image'], df['Steer'], test_size=0.2, random_state=1)

train_df=pd.DataFrame(columns=['id','steer'])
train_df['id']=train_x
train_df['steer']=train_y

test_df=pd.DataFrame(columns=['id','steer'])
test_df['id']=test_x
test_df['steer']=test_y

images_dir = '/content/original/compressed/All_data/'
train_datagen = ImageDataGenerator(rescale = 1./255)
train_generator = train_datagen.flow_from_dataframe(dataframe=train_df, directory=images_dir,
x_col="id", y_col="steer", has_ext=True,
class_mode="other", target_size=(110, 220),
batch_size=32)

test_datagen = ImageDataGenerator(rescale = 1./255)
test_generator = test_datagen.flow_from_dataframe(dataframe=test_df, directory=images_dir,
x_col="id", y_col="steer", has_ext=True,
class_mode="other", target_size=(110, 220),
batch_size=32)
import numpy as np
import pandas as pd

from skimage.transform import resize

import keras
from keras.models import Sequential, Model, load_model
from keras.layers import Input, Conv1D, Conv2D, MaxPooling1D, MaxPooling2D, Dense, Dropout, Activation, Flatten
from keras.layers.normalization import BatchNormalization
from keras.utils import to_categorical
from skimage.transform import resize
from tensorflow.keras import layers
import tensorflow as tf

from keras.applications import VGG16

# include top should be False to remove the softmax layer
pretrained_model = VGG16(include_top=False, weights='imagenet')

base_model = VGG16(input_shape = (110, 220, 3), # Shape of our images
include_top = False, # Leave out the last fully connected layer
weights = 'imagenet')

for layer in base_model.layers:
layer.trainable = False

from tensorflow.keras import layers
import tensorflow as tf

# Flatten the output layer to 1 dimension
x = layers.Flatten()(base_model.output)

# Add a fully connected layer with 512 hidden units and ReLU activation
x = layers.Dense(512, activation='relu')(x)

# Add a dropout rate of 0.5
x = layers.Dropout(0.5)(x)

# Add a final sigmoid layer for classification
x = layers.Dense(1, activation='linear')(x)

model = tf.keras.models.Model(base_model.input, x)
model.compile(loss = 'mean_absolute_percentage_error',optimizer=opt,metrics = ['mae'])

batch_size=128
history=model.fit(train_generator,
epochs = 15,
verbose = 1,
validation_data = test_generator
)

When I train the model using this code, a value of 0.221 is returned for the MAE for each epoch no matter what I do. I have changed the activation functions, optimizers, learning rate, etc but the result is the same every time. Am I loading in the data in a correct way?

When you are using a pre-trained model, you should use it's specific pre-processing function,

Below is an example for resnet50.

from keras.applications.resnet50 import preprocess_input
train_datagen = ImageDataGenerator(#rescale = 1./255
preprocessing_function=preprocess_input)

Always display/print your image/label for a sanity check.
You may use the below snippet.

#Quick check the DataGenerator

import matplotlib.pyplot as plt
for image, label in train_generator:
plt.imshow(image[0])
print(label[0])
break;


text:
# Chapter 4（2）：Tetris 俄罗斯方块

## Tetris, Tetris, Tetris!

Enough with all the helper classes and game components discussions. It is time to write another cool game. Thanks to the many classes available in the little game engine it is now easy to write text on the screen, draw sprites, handle input, and play sounds.

Before going into the details of the Tetris game logic, it would be useful to think about the placement of all game elements in a similar way you did in the previous games. Instead of drawing all game components on the screen, you just show the background boxes to see what is going to be displayed. For the background you use the space background once again (I promise, this will be the last time). The background box is a new texture and exists in two modes (see Figure 4-7). It is used to separate the game components and make everything fit much nicer on the screen. You could also just reuse the same box for both parts of the game, but because the aspect ratio is so different for them it would either look bad for the background box or for the extra game components, which are smaller, but also need the background box graphic, just a smaller version of it.

Figure 4-7

### Rendering the Background

To render these boxes on the screen you use the SpriteHelper class again and test everything with help of the following unit test:

public static void TestBackgroundBoxes()
{
TestGame.Start(
"TestBackgroundBoxes",

delegate

{

// Render background
TestGame.game.background.Render();

// Draw background boxes for all the components

// 为所有组件绘制背景框
TestGame.game.backgroundBigBox.Render(new Rectangle(
(
512 - 200- 1540 - 12400 + 23, (768 - 40+ 16));
TestGame.game.backgroundSmallBox.Render(
new Rectangle(
(
512 - 480- 1540 - 10290 - 30300));
TestGame.game.backgroundSmallBox.Render(
new Rectangle(
(
512 + 240- 1540 - 10290 - 30190));
}
);
}
// TestBackgroundBoxes()

This unit test will produce the output shown in Figure 4-8.

Figure 4-8

You might ask why the right box is a little bit smaller and where I got all these values from. Well, I just started with some arbitrary values and then improved the values until everything in the final game fit. First, the background is drawn in the unit test because you will not call the Draw method of TetrisGame if you are in the unit test (otherwise the unit tests won’t work anymore later when the game is fully implemented).

Then three boxes are drawn. The upper-left box is used to show the next block. The center box shows the current Tetris grid. And finally, the upper-right box is used to display the scoreboard. You already saw the unit test for that earlier.

### Handling the Grid

It is time to fill the content of these boxes. Start with the main component: the TetrisGrid. This class is responsible for displaying the whole Tetris grid. It handles the input and moves the falling block and it shows all the existing data as well. You already saw which methods are used in the TetrisGrid class in the discussion about the game components. Before rendering the grid you should check out the first constants defined in the TetrisGrid class:

Constants

There are a couple more interesting constants, but for now you only need the grid dimensions. So you have 12 columns and 20 lines for your Tetris field. With help of the Block.png texture, which is just a simple quadratic block, you can now easily draw the full grid in the Draw method:

// Calc sizes for block, etc.
int blockWidth = gridRect.Width / GridWidth;
int blockHeight = gridRect.Height / GridHeight;
for ( int x=0; x<GridWidth; x++ )

for ( int y=0; y<GridHeight; y++ )

{
game.BlockSprite.Render(
new Rectangle(
gridRect.X
+ x * blockWidth,
gridRect.Y
+ y * blockHeight,
blockWidth
-1, blockHeight-1),

new Color(606060128)); // Empty color
}
// for for

The gridRect variable is passed as a parameter to the Draw method from the main class to specify the area where you want the grid to be drawn to. It is the same rectangle as you used for the background box, just a little bit smaller to fit in. The first thing you are doing here is calculating the block width and height for each block you are going to draw. Then you go through the whole array and draw each block with the help of the SpriteHelper.Render method using a half transparent dark color to show an empty background grid. See Figure 4-9 to see how this looks. Because of the fact that you use game components you also don’t have to do all this code in your unit test. The unit test just draws the background box and then calls the TetrisGrid.Draw method to show the results (see the TestEmptyGrid unit test).

gridRect变量作为一个参数被从main类传递到Draw方法中来指定你要绘制各自的区域。这个是和你用来绘制背景框一样的矩形，只是更小一些。这里你要做的第一件事是为每一个要绘制的方块计算的宽和高。然后你要仔细检查整个数组并使用SpriteHelper.Render绘制每一个方块，使用半透明的暗色来呈现一个空的背景格。你会得到图4-9的效果。因为你使用了组件所以你不需要在单元测试中写完这些代码。单元测试只是绘制背景框然后调用TetrisGrid.Draw方法来显示结果（去看TestEmptyGrid单元测试）。

Figure 4-9

### Block Types

Before you can render anything useful on your new grid you should think about the block types you can have in your game. The standard Tetris game has seven block types; all of them consist of four small blocks connected to each other (see Figure 4-10). The most favorite block type is of course the line type because you can kill up to four lines with that giving you the most points.

Figure 4-10

These block types have to be defined in the TetrisGrid class. One way of doing that is to use an enum holding all the possible block types. This enum can also hold an empty block type allowing you to use this data structure for the whole grid too because each grid block can contain either any part of the predefined block types or it is empty. Take a look at the rest of the constants in the TetrisGrid class:

/// <summary>
/// Block types we can have for each new block that falls down.
/// 每一种可以下落的砖块的类型
/// </summary>

public enum BlockTypes
{
Empty,
Block,
Triangle,
Line,
RightT,
LeftT,
RightShape,
LeftShape,
}
// enum BlockTypes

/// <summary>
/// Number of block types we can use for each grid block.
/// 我们可以使用的砖块种类的数目
/// </summary>

public static readonly int NumOfBlockTypes =
EnumHelper.GetSize(
typeof(BlockTypes));

/// <summary>
/// Block colors for each block type.
/// 每一种砖块的颜色
/// </summary>

public static readonly Color[] BlockColor = new Color[]

{

new Color( 606060128 ), // Empty, color unused
new Color( 5050255255 ), // Line, blue
new Color( 160160160255 ), // Block, gray
new Color( 2555050255 ), // RightT, red
new Color( 25525550255 ), // LeftT, yellow
new Color( 50255255255 ), // RightShape, teal
new Color( 25550255255 ), // LeftShape, purple
new Color( 5025550255 ), // Triangle, green
}
// Color[] BlockColor
/// <summary>
/// Unrotated shapes
/// 未旋转的形状
/// </summary>

public static readonly int[][,] BlockTypeShapesNormal = new int[][,]

{

// Empty
new int[,] 0 } },

// Line
new int[,] 010 }010 }010 }010 } },

// Block
new int[,] 11 }11 } },

// RightT
new int[,] 11 }10 }10 } },

// LeftT
new int[,] 11 }01 }01 } },

// RightShape
new int[,] 011 }110 } },

// LeftShape
new int[,] 110 }011 } },

// Triangle
new int[,] 010 }111 }000 } },
}
// BlockTypeShapesNormal

BlockTypes is the enum we talked about; it contains all the possible block types and also is used to randomly generate new blocks in the NextBlock game component. Initially all of the grid fields are filled with the empty block type. The grid is defined as:

BlockTypes就是我们索道的枚举；它包含所有可能的砖块类型，也用于在NextBlock组件中随机生成新的砖块。一开始所有的格子区域都被空块类型填充满了。格子是这样定义的：

/// <summary>
/// The actual grid, contains all blocks,
/// including the currently falling block.
/// 实际的格子包含所有的砖块，也包括现在正在下落的砖块
/// </summary>

BlockTypes[,] grid = new BlockTypes[GridWidth, GridHeight];

By the way, NumOfBlockTypes shows you the usefulness of the enum class. You can easily determine how many entries are in the BlockTypes enum.

Next the colors for each block type are defined. These colors are used for the NextBlock preview, but also for rendering the whole grid. Each grid has a block type and you can easily use the BlockColors by converting the enum to an int number, which is used in the Draw method:

BlockColor[(int)grid[x,y]]

And finally the block shapes are defined, which looks a little bit more complicated, especially if you take into consideration that you have to allow these block parts to be rotated. This is done with help of the BlockTypeShapes, which is a big array of all possible blocks and rotations calculated in the constructor of TetrisGrid.

To add a new block to the Tetris grid you can just add each of the block parts to your grid, which is done in the AddRandomBlock method. You keep a separate list called floatingGrid to remember which parts of the grid have to be moved down (see the following section, “Gravity”; you can’t just let everything fall down) each time Update is called:

// Randomize block type and rotation
// 随机化砖块类型和旋转
currentBlockType = (int)nextBlock.SetNewRandomBlock();
currentBlockRot
= RandomHelper.GetRandomInt(4);

// Get precalculated shape
// 获得预先计算好的形状
int[,] shape = BlockTypeShapes[currentBlockType,currentBlockRot];
int xPos = GridWidth/2-shape.GetLength(0)/2;
// Center block at top most position of our grid
currentBlockPos = new Point(xPos, 0);

for ( int x=0; x<shape.GetLength(0); x++ )

for ( int y=0; y<shape.GetLength(1); y++ )

if ( shape[x,y] > 0 )

{

// Check if there is already something
if (grid[x + xPos, y] != BlockTypes.Empty)

{

// Then game is over dude!
gameOver = true;
Sound.Play(Sound.Sounds.Lose);
}
// if
else

{
grid[x
+ xPos, y] = (BlockTypes)currentBlockType;
floatingGrid[x
+ xPos, y] = true;
}
// else
}
// for for if

First you determine which block type you are going to add here. To help you do that you have a helper method in the NextBlock class, which randomizes the next block type and returns the last block type that was displayed in the NextBlock window. The rotation is also randomized; say “Hi” to the RandomHelper class.

With that data you can now get the precalculated shape and put it centered on the top of your grid. The two for loops iterate through the whole shape. It adds each valid part of the shape until you hit any existing data in the grid. In case that happens the game is over and you hear the lose sound. This will happen if the pile of blocks reaches the top of the grid and you cannot add any new blocks.

You now have the new block on your grid, but it is boring to just see it on the top there; it should fall down sometimes.

### Gravity

To test the gravity of the current block the TestFallingBlockAndLineKill unit test is used. The active block is updated each time you call the Update method of TetrisGrid, which is not very often. In the first level the Update method is called only every 1000ms (every second). There you check if the current block can be moved down:

TestFallingBlockAndLineKill单元测试用来测试当前砖块的下落引力。每一次当你调用TetrisGridUpdate方法是当前活动的砖块就会被更新。在第一等级每1000毫秒调用一次Update方法。这里你要检查砖块是否正常向下移动：

// Try to move floating stuff down
if (MoveBlock(MoveTypes.Down) == false ||
movingDownWasBlocked)
{

// Failed? Then fix floating stuff, not longer moveable!
for ( int x=0; x<GridWidth; x++ )

for ( int y=0; y<GridHeight; y++ )
floatingGrid[x,y]
= false;
Sound.Play(Sound.Sounds.BlockFalldown);
}
// if
movingDownWasBlocked = false;

Most of the Tetris logic is done in the MoveBlock helper method, which checks if moving in a specific direction is possible at all. If the block can’t be moved anymore it gets fixed and you clear the floatingGrid array and play the sound for landing a block on the ground.

Tetris的逻辑部分大多在MoveBlock辅助方法中完成，这个方法检查在指定方向上的移动是否可能。如果砖块不再能移动它将被固定然后你要清空floatingGrid数组然后播放砖块触底的声音。

After clearing the floatingGrid array there is no active block you can move down and the following code is used to check if a line was destroyed:

// Check if we got any moveable stuff,
// if not add new random block at top!
// 检查是我们是否还有可以移动的砖块，如果没有了，就在顶部随机生成一个砖块
bool canMove = false;
for ( int x=0; x<GridWidth; x++ )

for ( int y=0; y<GridHeight; y++ )

if ( floatingGrid[x,y] )
canMove
= true;

if (canMove == false)
{

int linesKilled = 0;

// Check if we got a full line
for ( int y=0; y<GridHeight; y++ )

{

bool fullLine = true;

for ( int x=0; x<GridWidth; x++ )

if ( grid[x,y] == BlockTypes.Empty )

{
fullLine
= false;

break;
}
// for if

// We got a full line?
// 有一个满行？
if (fullLine)

{

// Move everything down

// 将所有的都向下移动
for ( int yDown=y-1; yDown>0; yDown - )

for ( int x=0; x<GridWidth; x++ )
grid[x,yDown
+1= grid[x,yDown];

// Clear top line

// 清除顶行
for ( int x=0; x<GridWidth; x++ )
grid[
0,x] = BlockTypes.Empty;

// Add 10 points and count line

// 增加10分和消除的行数
score += 10;
lines
++;
linesKilled
++;
Sound.Play(Sound.Sounds.LineKill);
}
// if
}
// for

// If we killed 2 or more lines, add extra score
// 如果一次清楚超过2行，有额外加分
if (linesKilled >= 2)
score
+= 5;

if (linesKilled >= 3)
score
+= 10;

if (linesKilled >= 4)
score
+= 25;

// Add new block at top
// 在顶部添加新砖块
}
// if

The first thing that is done here is to check if there is an active moving block. If not you go into the “if block,” checking if a full line is filled and can be destroyed. To determine if a line is filled you assume it is filled and then check if any block of the line is empty. Then you know that this line is not fully filled and continue checking the next line. If the line is filled, however, you remove it by copying all the lines above it down. This is the place where a nice explosion could occur. Anyway, the player gets 10 points for this line kill, and you hear the line kill sound.

If the player was able to kill more than one line he gets awarded more points. And finally the AddRandomBlock method you saw before is used to create a new block at the top.

### Handling Input

Handling the user input itself is no big task anymore thanks to the Input helper class. You can easily check if a cursor or gamepad key was just pressed or is being held down. Escape and Back are handled in the BaseGame class and allow you to quit the game. Other than that you only need four keys in your Tetris game. To move to the left and right the cursor keys are used. The up cursor key is used to rotate the current block and the down cursor key or alternatively the space or A keys can be used to let the block fall down faster.

Similar to the gravity check to see if you can move the block down, the same check is done to see if you can move the current block left or right. Only if that is true do you actually move the block; this code is done in the TetrisGame Update method because you want to check for the player input every frame and not just when updating the TetrisGrid, which can only happen every 1000ms as you learned before. The code was in the TetrisGrid Update method before, but to improve the user experience it was moved and improved quite a lot also allowing you to move the block quickly left and right by hitting the cursor buttons multiple times.

Well, you have learned a lot about all the supporting code and you are almost doneto run the Tetris game for the first time. But you should take a look at the MoveBlock helper method because it is the most integral and important part of your Tetris game. Another important method is the RotateBlock method, which works in a similar way testing if a block can be rotated. You can check it out yourself in the source code for the Tetris game. Please use the unit tests in the TetrisGame class to see how all these methods work:

Move block

There are three kinds of moves you can do: Left, Right, and Down. Each of these moves is handled in a separate code block to see if the left, right, or down data is available and if it is possible to move there. Before going into the details of this method there are two things that should be mentioned. First of all there is a helper variable called movingDownWasBlocked defined above the method. The reason you have this variable is to speed up the process of checking if the current block reached the ground, and it is stored at the class level to let the Update method pick it up later (which can be several frames later) and make the gravity code you saw earlier update much faster than in the case when the user doesn’t want to drop the block down right here. This is a very important part of the game because if each block were immediately fixed when reaching the ground the game would become very hard, and all the fun is lost when it gets faster and the grid gets more filled.

Then you use another trick to simplify the checking process by temporarily removing the current block from the grid. This way you can easily check if a new position is possible because your current position does not block you anymore. The code also uses several helper variables to store the new position and that code is simplified a bit to account for only four block parts. If you change the block types and the number of block parts, you should also change this method.

After setting everything up you check if the new virtual block position is possible in the three code blocks. Usually it is possible and you end up with four new values in the newPosNum array. If there are less than three values available you know that something was blocking you and the anythingBlocking variable is set to true anyway. In that case the old block position is restored and both the grid and the floatingGrid arrays stay the same way.

But in case the move attempt was successful the block position is updated and you clear the floatingGrid and finally add the block again to the new position by adding it both to the grid and the floatingGrid. The user also hears a very silent block move sound and you are done with this method.

【但是万一移动的尝试成功了，砖块的位置被更新了倪还清空了floatingGrid数组，最后又一次在gridfloatingGrid中添加了砖块到新的位置。用户同样会听到一声轻微的移动的声效，你使用这个方法来完成。】

### Testing

With all that new code in the TetrisGrid class you can now test the unit tests in the TetrisGame class. In addition to the tests you saw before the two most important unit tests for the game logic are:

§  TestRotatingBlock, which tests the RotateBlock method of the TetrisGrid class.

TestRotatingBlock，用来测试TetrisGrid类中的RotateBlock方法。

§  TestFallingBlockAndKillLine, which is used to test the gravity and user input you just learned about.

TestFallingBlockAndKillLine用来测试引力下落和刚刚学到的用户输入。

It should be obvious that you often go back to older unit tests to update them according to the newest changes you require for your game. For example, the TestBackgroundBoxes unit test you saw earlier is very simple, but the layout and position of the background boxes changed quite a lot while implementing and testing the game components and it had to be updated accordingly to reflect the changes. One example for that would be the scoreboard, which is surrounded by the background box, but before you can know how big the scoreboard is going to be you have to know what the contents are and how much space they are going to consume. After writing the TestScoreboard method it became very obvious that the scoreboard has to be much smaller than the NextBlock background box, for example.

Another part of testing the game is constantly checking for bugs and improving the game code. The previous games were pretty simple and you only had to make minor improvements after the first initial runs, but the Tetris game is much more complex and you can spend many hours fixing and improving it.

One last thing you could test is running the game on the Xbox 360 - just select the Xbox 360 console platform in the project and try to run it on the Xbox 360. All the steps to do that were explained in Chapter 1, which also has a useful troubleshooting section in case something does not work on the Xbox 360. If you write new code you should make sure from time to time that it compiles on the Xbox 360 too. You are not allowed to write any interop code calling unmanaged assemblies, and some of the .NET 2.0 Framework classes and methods are missing on the Xbox 360.

• 本文已收录于以下专栏：

## CCF 历年真题之俄罗斯方块（_1604_2_Tetris.java）参考答案

CCF 历年真题之俄罗斯方块（_1604_2_Tetris）参考答案 问题描述 试题编号： 201604-2 试题名称： 俄罗斯方块 时间限制： 1.0s 内存限制： 256....
• Dina_p
• 2017年07月10日 16:34
• 410

## JS/Jquery版本的俄罗斯方块(Tetris)

1.前言 写这个Jquery版本的小游戏的缘由在于我想通过从零到有，自己写一个Jquery版本的游戏用来练手。 经历了V1，V2版本，当前版本是V3。 游戏功能：关卡，分数，暂停，虚拟键，状态栏，自定...

## HDU 5374 Tetris(模拟俄罗斯方块）

Tetris God Wu enjoy coding some trivial games like Tetris.His Tetris is made up by 9 columns and 12 ...

## JavaScript jQuery实现Tetris(俄罗斯方块)游戏代码

举报原因： 您举报文章：Chapter 4（2）：Tetris 俄罗斯方块 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)


text:
2,621 Answered Questions for the topic elementary math

Elementary Math

4d

Rebecca bought 50 oz of flour for her bakery. She used 18.5 oz to make a loaf of bread, and 1.02 oz for each muffin. How many muffins did Rebecca make if she had 17.22 oz of flour left over?
Elementary Math

5d

#### help with homework

what is the perimeter of a 4 x 4 centimeter square
Elementary Math

9d

You have a board that is 7 feet. You cut 1/3 foot pieces. How many pieces do you have?
Elementary Math

16d

Tiff has 3 pizza she wants to give equally to 6 friends how much pizza will each friend get
Elementary Math

17d

#### If I can buy 219x for 0.41y, how many of x can I get for 1y?

0.41y = 219x1y = ? What is 1y?
Elementary Math

04/28/22

#### I need help with my homework

This is the math problom 1 2/3 - 3/4=
Elementary Math

04/27/22

Ava wants to save up money to buy an Ipad. She saves $20 each week. Write an equation that represents the relationship between the total amount of money Ava saves and the amount of weeks she saves... more Elementary Math 04/26/22 #### How much would it cost to buy x pounds of oranges? If oranges were 1.25$

Problem. needed for homework
Elementary Math

04/22/22

#### Math #3 Grade School Prodigy

What is the sum of 35 and diff. of 6.
Elementary Math

04/22/22

#### mathismathbecasue

The area of the rug measures 96 square feet what could the length and width of the rug be
Elementary Math

04/20/22

#### Challenge word problem

Lincoln says "If I had picked 50% more apples, I would have picked 30 apples." How many apples did Lincoln pick?
Elementary Math

04/19/22

#### Math for elementary

Your third-grade classroom has 23 boys and girls. Two thirds of the boys and three fourths of the girls are going on a field trip. There are 7 children left. What is the ratio boys to... more
Elementary Math

04/18/22

#### If it takes 2/3 of an hour to mow 4/5 of a lawn, then how many acres can you mow in an hour?

I need to write an equation for the word problem.
Elementary Math Math Algebra Maths

04/17/22

#### Could I have an explanation of how to solve this question?

A manufacturing machine has a 5% defect rate.If 9 items are chosen at random, what is the probability that at least one will have a defect?
Elementary Math Math Algebra Mathematics

04/17/22

#### Could I get an explanation for this question?

A high school baseball player has a 0.167 batting average. In one game, he gets 9 at bats. What is the probability he will get at least 5 hits in the game?
Elementary Math

04/10/22

#### math ratios and rates

While researching universities joe learns that a typical class at york university has 7 men and 4 women, and a typical class at the university of toronto has 19 men and 9 women. Do the universities... more

04/07/22

#### Can you please answer my question? What is 1 + 1? I NEED help!

I really need to know what it is.

## Still looking for help? Get the right answer, fast.

Get a free answer to a quick problem.
Most questions answered within 4 hours.

#### OR

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.


text:
# Question #70353

Feb 8, 2017

$\left(y - \textcolor{red}{4}\right) = \textcolor{b l u e}{- 10} \left(x - \textcolor{red}{1}\right)$

#### Explanation:

The point-slope formula states: $\left(y - \textcolor{red}{{y}_{1}}\right) = \textcolor{b l u e}{m} \left(x - \textcolor{red}{{x}_{1}}\right)$

Where $\textcolor{b l u e}{m}$ is the slope and $\textcolor{red}{\left(\left({x}_{1} , {y}_{1}\right)\right)}$ is a point the line passes through.

Substituting the values from the problem gives:

$\left(y - \textcolor{red}{4}\right) = \textcolor{b l u e}{- 10} \left(x - \textcolor{red}{1}\right)$


text:
A thin wrapper around gam, however, some arguments are prespecified: family=poisson(), offset=data\$offset and method="REML". The first two can not be overwritten. The method argument can be specified as usual, but defaults to GCV.cp in gam.

pamm(
formula,
data = list(),
method = "REML",
...,
trafo_args = NULL,
engine = "gam"
)

is.pamm(x)

# S3 method for pamm
print(x, ...)

# S3 method for pamm
summary(object, ...)

# S3 method for pamm
plot(x, ...)

## Arguments

formula A GAM formula, or a list of formulae (see formula.gam and also gam.models). These are exactly like the formula for a GLM except that smooth terms, s, te, ti and t2, can be added to the right hand side to specify that the linear predictor depends on smooth functions of predictors (or linear functionals of these). A data frame or list containing the model response variable and covariates required by the formula. By default the variables are taken from environment(formula): typically the environment from which gam is called. The smoothing parameter estimation method. "GCV.Cp" to use GCV for unknown scale parameter and Mallows' Cp/UBRE/AIC for known scale. "GACV.Cp" is equivalent, but using GACV in place of GCV. "REML" for REML estimation, including of unknown scale, "P-REML" for REML estimation, but using a Pearson estimate of the scale. "ML" and "P-ML" are similar, but using maximum likelihood in place of REML. Beyond the exponential family "REML" is the default, and the only other option is "ML". Further arguments passed to engine. A named list. If data is not in PED format, as_ped will be called internally with arguments provided in trafo_args. Character name of the function that will be called to fit the model. The intended entries are either "gam" or "bam" (both from package mgcv). Any R object. An object of class pamm as returned by pamm.

gam

## Examples

ped <- tumor[1:100, ] %>%
as_ped(Surv(days, status) ~ complications, cut = seq(0, 3000, by = 50))
pam <- pamm(ped_status ~ s(tend) + complications, data = ped)
summary(pam)
#>
#> Family: poisson
#>
#> Formula:
#> ped_status ~ s(tend) + complications
#>
#> Parametric coefficients:
#>                  Estimate Std. Error z value Pr(>|z|)
#> (Intercept)       -7.8839     0.1969 -40.038   <2e-16 ***
#> complicationsyes   0.2453     0.3420   0.717    0.473
#> ---
#> Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#>
#> Approximate significance of smooth terms:
#>           edf Ref.df Chi.sq p-value
#> s(tend) 1.001  1.003  5.456  0.0196 *
#> ---
#> Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#>
#> R-sq.(adj) =  -0.0232   Deviance explained = 1.87%
#> UBRE = -0.79402  Scale est. = 1         n = 1937## Alternatively
pamm(
ped_status ~ s(tend) + complications,
data = tumor[1:100, ],
trafo_args = list(formula = Surv(days, status)~complications))
#>
#> Family: poisson
#> UBRE score: -0.8570005


text:
• # question_answer The side of a square is 5 cm. How many times does the area increase, if the side of the square is doubled?

Given,   side of square = 5 cm $\therefore$      Area of square $=side\times side$            $=5\times 5$            $=25\text{ }sq\text{ }cm$                                                                                Now according to question, New side $=2\times$initial side   $=2\times 5$    $=10\text{ }cm$                                                                                $\therefore$ Area of new square $=side\times side$           $=10\times 10$            $=100\text{ }sq\text{ }cm$.                                                                                $\therefore$ $\frac{\text{Area}\,\,\text{of}\,\,\text{new}\,\,\text{square}}{\text{Area}\,\,\text{of}\,\,\text{old}\,\,\text{square}}=\frac{100}{25}=4$ Hence, the area of new square is 4 times increase.

You need to login to perform this action.
You will be redirected in 3 sec


text:
# idnlarx

Nonlinear ARX model

## Description

An idnlarx model represents a nonlinear ARX model, which is an extension of the linear ARX structure and contains linear and nonlinear functions.

A nonlinear ARX model consists of model regressors and an output function. The output function contains one or more mapping objects, one for each model output. Each mapping object can include a linear and a nonlinear function that act on the model regressors to give the model output and a fixed offset for that output. This block diagram represents the structure of a single-output nonlinear ARX model in a simulation scenario.

The software computes the nonlinear ARX model output y in two stages:

1. It computes regressor values from the current and past input values and the past output data.

In the simplest case, regressors are delayed inputs and outputs, such as u(t–1) and y(t–3). These kind of regressors are called linear regressors. You specify linear regressors using the linearRegressor object. You can also specify linear regressors by using linear ARX model orders as an input argument. For more information, see Nonlinear ARX Model Orders and Delay. However, this second approach constrains your regressor set to linear regressors with consecutive delays. To create polynomial regressors, use the polynomialRegressor object. To create periodic regressors that contain the sine and cosine functions of delayed input and output variables , use the periodicRegressor object. You can also specify custom regressors, which are nonlinear functions of delayed inputs and outputs. For example, u(t–1)y(t–3) is a custom regressor that multiplies instances of input and output together. Specify custom regressors using the customRegressor object.

You can assign any of the regressors as inputs to the linear function block of the output function, the nonlinear function block, or both.

2. It maps the regressors to the model output using an output function block. The output function block can include multiple mapping objectslinear, nonlinear, and offset blocks in parallel. For example, consider the following equation:

$F\left(x\right)={L}^{T}\left(x-r\right)+g\left(Q\left(x-r\right)\right)+d$

Here, x is a vector of the regressors, and r is the mean of x. $F\left(x\right)={L}^{T}\left(x-r\right)+{y}_{0}$ is the output of the linear function block. $g\left(Q\left(x-r\right)\right)+{y}_{0}$ represents the output of the nonlinear function block. Q is a projection matrix that makes the calculations well-conditioned. d is a scalar offset that is added to the combined outputs of the linear and nonlinear blocks. The exact form of F(x) depends on your choice of output function. You can select from the available mapping objects, such as tree-partition networks, wavelet networks, and multilayer neural networks. You can also exclude either the linear or the nonlinear function block from the output function.

When estimating a nonlinear ARX model, the software computes the model parameter values, such as L, r, d, Q, and other parameters specifying g.

The resulting nonlinear ARX models are idnlarx objects that store all model data, including model regressors and parameters of the output function. For more information about these objects, see Nonlinear Model Structures.

For more information on the idnlarx model structure, see What are Nonlinear ARX Models?.

For idnlarx object properties, see Properties.

## Creation

You can obtain an idnlarx object in one of two ways.

• Use the nlarx command to both construct an idnlarx object and estimate the model parameters.

sys = nlarx(data,reg)

• Use the idnlarx constructor to create the nonlinear ARX model and then estimate the model parameters using nlarx or pem.

sys = idnlarx(output_name,input_name,reg)

### Description

#### Specify Model Directly

example

sys = idnlarx(output_name,input_name,orders) specifies a set of linear regressors using ARX model orders. Use this syntax when you extend an ARX linear model, or when you plan to use only regressors that are linear with consecutive lags.

example

sys = idnlarx(output_name,input_name,Regressors) creates a nonlinear ARX model with the output and input names of output_name and input_name, respectively, and a regressor set in Regressors that contains any combination of linear, polynomial, periodic, and custom regressors. The software constructs sys using the default wavelet network ('idWaveletNetwork') mapping object for the output function.

example

sys = idnlarx(___,OutputFcn) specifies the output function OutputFcn that maps the regressors to the model output. You can use this syntax with any of the previous input argument combinations.

#### Initialize Model Values Using Linear Model

example

sys = idnlarx(linmodel) uses a linear model linmodel to extract certain properties such as names, units, and sample time, and to initialize the values of the linear coefficients of the model. Use this syntax when you want to create a nonlinear ARX model as an extension of, or an improvement upon, an existing linear model.

example

sys = idnlarx(linmodel,OutputFcn) specifies the output function OutputFcn that maps the regressors to the model output.

#### Specify Model Properties

sys = idnlarx(___,Name,Value) specifies additional properties of the idnlarx model structure using one or more name-value arguments.

### Input Arguments

expand all

ARX model orders, specified as the matrix [na nb nk]. na denotes the number of delayed outputs, nb denotes the number of delayed inputs, and nk denotes the minimum input delay. The minimum output delay is fixed to 1. For more information on how to construct the orders matrix, see arx.

When you specify orders, the software converts the order information into a linear regressor form in the idnlarx Regressors property. For an example, see Create Nonlinear ARX Model Using ARX Model Orders.

Discrete-time identified input/output linear model, specified as any linear model created using estimators, that is, an idpoly object, an idss object, an idtf object, or an idproc object with Ts > 0. Create this model using the constructor function for the object or estimate the model using the associated estimation command. For example, to create an ARX model, use arx, and specify the resulting idpoly object as linmodel.

## Properties

expand all

Regressor specification, specified as a column vector containing one or more regressor specification objects, which are the linearRegressor objects, polynomialRegressor objects, periodicRegressor objects, and customRegressor objects. Each object specifies a formula for generating regressors from lagged variables. For example:

• L = linearRegressor({'y1','u1'},{1,[2 5]}) generates the regressors y1(t–1), u1(t–2), and u2(t–5).

• P = polynomialRegressor('y2',4:7,2) generates the regressors y2(t–4)2, y2(t–5)2,y2(t–6)2, and y2(t–7)2.

• SC = periodicRegressor({'y1','u1'},{1,2}) generates the regressors y1(t-1)), cos(y1(t-1)), sin(u1(t-2)), and cos(u1(t-2)).

• C = customRegressor({'y1','u1','u2'},{1 2 2},@(x,y,z)sin(x.*y+z)) generates the single regressor sin(y1(t–1)u1(t–2)+u2(t–2)

.

For an example that implements these regressors, see Create and Combine Regressor Types.

To add regressors to an existing model, create a vector of specification objects and use dot notation to set Regressors to this vector. For example, the following code first creates the idnlarx model sys and then adds the regressor objects L, P, SC, and C to the regressors of sys.

sys = idnlarx({'y1','y2'},{'u1','u2'});
R = [L;P;SC;C];
sys.Regressors = R;

For an example of creating and using a linear regressor set, see Create Nonlinear ARX Model Using Linear Regressors.

Output function that maps the regressors of the idnlarx model into the model output, specified as a column array containing zero or more of the following strings or mapping objects:

 'idWaveletNetwork' or idWaveletNetwork object Wavelet network 'idLinear' or '' or [] or idLinear object Linear function 'idSigmoidNetwork' or idSigmoidNetwork object Sigmoid network 'idTreePartition' or idTreePartition object Binary tree partition regression model 'idGaussianProcess' or idGaussianProcess object Gaussian process regression model (requires Statistics and Machine Learning Toolbox™) 'idTreeEnsemble' or idTreeEnsemble Regression tree ensemble model (requires Statistics and Machine Learning Toolbox) 'idSupportVectorMachine' or idSupportVectorMachine Kernel-based Support Vector Machine (SVM) regression model with constraints (requires Statistics and Machine Learning Toolbox) idFeedforwardNetwork object Neural network — Multilayer feedforward network of Deep Learning Toolbox™ idCustomNetwork object Custom network — Similar to idSigmoidNetwork, but with a user-defined replacement for the sigmoid function

The idWaveletNetwork, idSigmoidNetwork, idTreePartition, and idCustomNetwork objects contain both linear and nonlinear components. You can remove (not use) the linear components of idWaveletNetwork, idSigmoidNetwork, and idCustomNetwork by setting the LinearFcn.Use value to false.

The idFeedforwardNetwork object has only a nonlinear component that is the network (Deep Learning Toolbox) object of Deep Learning Toolbox. The idTreeEnsemble and idSupportVectorMachine objects also contain only a nonlinear component. The idLinear function, as the name implies, has only a linear component.

Specifying a character vector, for example 'idSigmoidNetwork', creates a mapping object with default settings. Alternatively, you can specify mapping object properties in two other ways:

• Create the mapping object using arguments to modify default properties.

MO = idSigmoidNetwork(15)
• Create a default mapping object first and then use dot notation to modify properties.

MO = idSigmoidNetwork;
MO.NumberOfUnits = 15

For ny output channels, you can specify mapping objects individually for each channel by setting OutputFcn to an array of ny mapping objects. For example, the following code specifies OutputFcn using dot notation for a system with two input channels and two output channels.

sys = idnlarx({'y1','y2'},{'u1','u2'});
sys.OutputFcn = [idWaveletNetwork; idSigmoidNetwork]
To specify the same mapping for all outputs, specify OutputFcn as a character vector or a single mapping object.

OutputFcn represents a static mapping function that transforms the regressors of the nonlinear ARX model into the model output. OutputFcn is static because it does not depend on the time. For example, if $y\left(t\right)={y}_{0}+{a}_{1}y\left(t-1\right)+{a}_{2}y\left(t-2\right)+\dots +{b}_{1}u\left(t-1\right)+{b}_{2}u\left(t-2\right)+\dots$, then OutputFcn is a linear function represented by the idLinear object.

For an example of specifying the output function, see Specify Output Function for Nonlinear ARX Model.

Regressor assignments to the linear and nonlinear components of the nonlinear ARX model, specified as an nr-by-nc table with logical entries that specify which regressors to use for which component. Here, nr is the number of regressors. nc is the total number of linear and nonlinear components in OutputFcn. The rows of the table correspond to individual regressors. The row names are set to regressor names. If the table value for row i and component index j is true, then the ith regressor is an input to the linear or nonlinear component j.

For multi-output systems, OutputFcn contains one mapping object for each output. Each mapping object can use both linear and nonlinear components or only one of the two components.

For an example of viewing and modifying the RegressorUsage property, see Modify Regressor Assignments to Output Function Components.

Regressor and output centering and scaling, specified as a structure. As the following table shows, each field in the structure contains a row vector with a length that is equal to the number of either regressors (nr) or model outputs (ny).

FieldDescriptionDefault Element Value
RegressorCenterRow vector of length nrNaN
RegressorScaleRow vector of length nrNaN
OutputCenterRow vector of length nyNaN
OutputScaleRow vector of length nyNaN

For a matrix X, with centering vector C and scaling vector S, the software computes the normalized form of X using Xnorm = (X-C)./S.

The following figure illustrates the normalization flow for a nonlinear ARX model.

In this figure:

1. The algorithm converts the inputs u(t) and y(t) into the regressor set R(t).

2. The algorithm uses the regressor centering and scaling parameters to normalize R(t) as RN(t).

3. RN(t) provides the input to the mapping function, which then produces the normalized output yN

4. The algorithm uses the output scaling and centering parameters to restore the original range, producing y(t).

Typically, the software normalizes the data automatically during model estimation, in accordance with the option settings in nlarxOptions for Normalize and NormalizationOptions. You can also directly assign centering and scaling values by specifying the values in vectors, as described in the previous table. The values that you assign must be real and finite. This approach can be useful, for example, when you are simulating your model using inputs that represent a different operating point from the operating point for the original estimation data. You can assign the values for any field independently. The software will estimate the values of any fields that remain unassigned (NaN).

Summary report that contains information about the estimation options and results for a nonlinear ARX model obtained using the nlarx command. Use Report to find estimation information for the identified model, including:

• Estimation method

• Estimation options

• Search termination conditions

• Estimation data fit

The contents of Report are irrelevant if the model was constructed using idnlarx.

sys = idnlarx('y1','u1',reg);
sys.Report.OptionsUsed
ans =

[]

If you use nlarx to estimate the model, the fields of Report contain information on the estimation data, options, and results.

sys = nlarx(z1,reg);
m.Report.OptionsUsed
Option set for the nlarx command:

IterativeWavenet: 'auto'
Focus: 'prediction'
Display: 'off'
Regularization: [1x1 struct]
SearchMethod: 'auto'
SearchOptions: [1x1 idoptions.search.identsolver]
OutputWeight: 'noise'

For more information on this property and how to use it, see Output Arguments in the nlarx reference page and Estimation Report.

Independent variable for the inputs, outputs, and—when available—internal states, specified as a character vector.

Noise variance (covariance matrix) of the model innovations e. The estimation algorithm typically sets this property. However, you can also assign the covariance values by specifying an ny-by-ny matrix.

Sample time, specified as a positive scalar representing the sampling period. This value is expressed in the unit specified by the TimeUnit property of the model.

Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of the following values:

• 'nanoseconds'

• 'microseconds'

• 'milliseconds'

• 'seconds'

• 'minutes'

• 'hours'

• 'days'

• 'weeks'

• 'months'

• 'years'

Changing this property has no effect on other properties, and therefore changes the overall system behavior. Use chgTimeUnit (Control System Toolbox) to convert between time units without modifying system behavior.

Input channel names, specified as one of the following:

• Character vector — For single-input models, for example, 'controls'.

• Cell array of character vectors — For multi-input models.

Input names in Nonlinear ARX models must be valid MATLAB® variable names after you remove any spaces.

Alternatively, use automatic vector expansion to assign input names for multi-input models. For example, if sys is a two-input model, enter:

sys.InputName = 'controls';

The input names automatically expand to {'controls(1)';'controls(2)'}.

When you estimate a model using an iddata object, data, the software automatically sets InputName to data.InputName.

You can use the shorthand notation u to refer to the InputName property. For example, sys.u is equivalent to sys.InputName.

Input channel names have several uses, including:

• Identifying channels on model display and plots

• Extracting subsystems of MIMO systems

• Specifying connection points when interconnecting models

Input channel units, specified as one of the following:

• Character vector — For single-input models, for example, 'seconds'.

• Cell array of character vectors — For multi-input models.

Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.

Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems into groups and refer to each group by name. Specify input groups as a structure. In this structure, field names are the group names, and field values are the input channels belonging to each group. For example:

sys.InputGroup.controls = [1 2];
sys.InputGroup.noise = [3 5];

creates input groups named controls and noise that include input channels 1, 2 and 3, 5, respectively. You can then extract the subsystem from the controls inputs to all outputs using:

sys(:,'controls')

Output channel names, specified as one of the following:

• Character vector — For single-output models. For example, 'measurements'.

• Cell array of character vectors — For multi-output models.

Output names in Nonlinear ARX models must be valid MATLAB variable names after you remove any spaces.

Alternatively, use automatic vector expansion to assign output names for multi-output models. For example, if sys is a two-output model, enter:

sys.OutputName = 'measurements';

The output names automatically expand to {'measurements(1)';'measurements(2)'}.

When you estimate a model using an iddata object, data, the software automatically sets OutputName to data.OutputName.

You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is equivalent to sys.OutputName.

Output channel names have several uses, including:

• Identifying channels on model display and plots

• Extracting subsystems of MIMO systems

• Specifying connection points when interconnecting models

Output channel units, specified as one of the following:

• Character vector — For single-output models. For example, 'seconds'.

• Cell array of character vectors — For multi-output models.

Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.

Output channel groups. The OutputGroup property lets you assign the output channels of MIMO systems into groups and refer to each group by name. Specify output groups as a structure. In this structure, field names are the group names, and field values are the output channels belonging to each group. For example:

sys.OutputGroup.temperature = [1];
sys.InputGroup.measurement = [3 5];

creates output groups named temperature and measurement that include output channels 1, and 3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs using:

sys('measurement',:)

System name, specified as a character vector. For example, 'system 1'.

Any text that you want to associate with the system, specified as a string or a cell array of character vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are dynamic system models, you can set their Notes properties as follows.

sys1.Notes = "sys1 has a string.";
sys2.Notes = 'sys2 has a character vector.';
sys1.Notes
sys2.Notes
ans =

"sys1 has a string."

ans =

'sys2 has a character vector.'

Any data you want to associate with the system, specified as any MATLAB data type.

## Object Functions

For information about object functions for idnlarx, see Nonlinear ARX Models.

## Examples

collapse all

Create an idnlarx model by specifying an ARX model order vector.

Create an order vector of the form [na nb nk], where na and nb are the orders of the A and B ARX model polynomials and nk is the number of input/output delays.

na = 2;
nb = 3;
nk = 5;
orders = [na nb nk];

Construct a nonlinear ARX model sys.

output_name = 'y1';
input_name = 'u1';

sys = idnlarx(output_name,input_name,[2 3 5]);

View the output function.

disp(sys.OutputFcn)
Wavelet Network

Nonlinear Function: Wavelet network with number of units chosen automatically
Linear Function: uninitialized
Output Offset: uninitialized

Inputs: {'y1(t-1)'  'y1(t-2)'  'u1(t-5)'  'u1(t-6)'  'u1(t-7)'}
Outputs: {'y1(t)'}
NonlinearFcn: '<Wavelet and scaling function units and their parameters>'
LinearFcn: '<Linear function parameters>'
Offset: '<Offset parameters>'
EstimationOptions: '<Estimation options>'

By default, the model uses a wavelet network, represented by a idWaveletNetwork object, for the output function. The idWaveletNetwork object includes linear and nonlinear components.

View the Regressors property.

disp(sys.Regressors)
Linear regressors in variables y1, u1
Variables: {'y1'  'u1'}
Lags: {[1 2]  [5 6 7]}
UseAbsolute: [0 0]
TimeVariable: 't'

The idnlarx constructor transforms the model orders into the Regressors form.

• The Lags array for y1, [1 2], is equivalent to the na value of 2. Both forms specify two consecutive output regressors, y1(t-1) and y1(t-2).

• The Lags array for u1, [5 6 7], incorporates the three delays specified by the nb value of 3, and shifts them by the nk value of 5. The input regressors are therefore u1(t-5), u1(t-6), and u1(t-7).

View the regressors.

getreg(sys)
ans = 5x1 cell
{'y1(t-1)'}
{'y1(t-2)'}
{'u1(t-5)'}
{'u1(t-6)'}
{'u1(t-7)'}

You can use the orders syntax to specify simple linear regressors. However, to create more complex regressors, use the regressor commands linearRegressor, polynomialRegressor, and customRegressor to create a combined regressor for the Regressors syntax.

Construct an idnlarx model by specifying linear regressors.

Create a linear regressor that contains two output lags and two input lags.

output_name = 'y1';
input_name = 'u1';
var_names = {output_name,input_name};

output_lag = [1 2];
input_lag = [1 2];
lags = {output_lag,input_lag};

reg = linearRegressor(var_names,lags)
reg =
Linear regressors in variables y1, u1
Variables: {'y1'  'u1'}
Lags: {[1 2]  [1 2]}
UseAbsolute: [0 0]
TimeVariable: 't'

Regressors described by this set

The model contains the regressors y(t-1), y(t-2), u(t-1), and u(t-2).

Construct the idnlarx model and view the regressors.

sys = idnlarx(output_name,input_name,reg);
getreg(sys)
ans = 4x1 cell
{'y1(t-1)'}
{'y1(t-2)'}
{'u1(t-1)'}
{'u1(t-2)'}

View the output function.

disp(sys.OutputFcn)
Wavelet Network

Nonlinear Function: Wavelet network with number of units chosen automatically
Linear Function: uninitialized
Output Offset: uninitialized

Inputs: {'y1(t-1)'  'y1(t-2)'  'u1(t-1)'  'u1(t-2)'}
Outputs: {'y1(t)'}
NonlinearFcn: '<Wavelet and scaling function units and their parameters>'
LinearFcn: '<Linear function parameters>'
Offset: '<Offset parameters>'
EstimationOptions: '<Estimation options>'

View the regressor usage table.

disp(sys.RegressorUsage)
y1:LinearFcn    y1:NonlinearFcn
____________    _______________

y1(t-1)       true              true
y1(t-2)       true              true
u1(t-1)       true              true
u1(t-2)       true              true

All the regressors are inputs to both the linear and nonlinear components of the wavenet object.

Create a nonlinear ARX model with a linear regressor set.

Create a linear regressor that contains three output lags and two input lags.

output_name = 'y1';
input_name = 'u1';
var_names = {output_name,input_name};

output_lag = [1 2 3];
input_lag = [1 2];
lags = {output_lag,input_lag};

reg = linearRegressor(var_names,lags)
reg =
Linear regressors in variables y1, u1
Variables: {'y1'  'u1'}
Lags: {[1 2 3]  [1 2]}
UseAbsolute: [0 0]
TimeVariable: 't'

Regressors described by this set

Construct the nonlinear ARX model.

sys = idnlarx(output_name,input_name,reg);

View the Regressors property.

disp(sys.Regressors)
Linear regressors in variables y1, u1
Variables: {'y1'  'u1'}
Lags: {[1 2 3]  [1 2]}
UseAbsolute: [0 0]
TimeVariable: 't'

sys uses idWavenetNetwork as the default output function. Reconfigure the output function to idSigmoidNetwork.

sys.OutputFcn = 'idSigmoidNetwork';
disp(sys.OutputFcn)
Sigmoid Network

Nonlinear Function: Sigmoid network with 10 units
Linear Function: uninitialized
Output Offset: uninitialized

Inputs: {'y1(t-1)'  'y1(t-2)'  'y1(t-3)'  'u1(t-1)'  'u1(t-2)'}
Outputs: {'y1(t)'}
NonlinearFcn: '<Sigmoid units and their parameters>'
LinearFcn: '<Linear function parameters>'
Offset: '<Offset parameters>'

Specify the sigmoid network output function when you construct a nonlinear ARX model.

Assign variable names and specify a regressor set.

output_name = 'y1';
input_name = 'u1';
r = linearRegressor({output_name,input_name},{1 1});

Construct a nonlinear ARX model that specifies the idSigmoidNetwork output function. Set the number of terms in the sigmoid expansion to 15.

sys = idnlarx(output_name,input_name,r,idSigmoidNetwork(15));

View the output function specification.

disp(sys.OutputFcn)
Sigmoid Network

Nonlinear Function: Sigmoid network with 15 units
Linear Function: uninitialized
Output Offset: uninitialized

Inputs: {'y1(t-1)'  'u1(t-1)'}
Outputs: {'y1(t)'}
NonlinearFcn: '<Sigmoid units and their parameters>'
LinearFcn: '<Linear function parameters>'
Offset: '<Offset parameters>'

Construct an idnlarx model that uses only linear mapping in the output function. An argument value of [] is equivalent to an argument value of idLinear.

sys = idnlarx([2 2 1],[])
sys =
Nonlinear ARX model with 1 output and 1 input
Inputs: u1
Outputs: y1

Regressors:
Linear regressors in variables y1, u1
List of all regressors

Output function: Linear with offset
Sample time: 1 seconds

Status:
Created by direct construction or transformation. Not estimated.

Create a regressor set that includes linear, polynomial, periodic, and custom regressors.

Specify L as the set of linear regressors ${\mathit{y}}_{1}\left(\mathit{t}-1\right)$, ${\mathit{u}}_{1}\left(\mathit{t}-2\right)$, and ${\mathit{u}}_{1}\left(\mathit{t}-5\right)$.

L = linearRegressor({'y1','u1'},{1, [2 5]});

Specify P as the set of polynomial regressors ${\mathit{y}}_{2}{\left(\mathit{t}-4\right)}^{2}$, ${\mathit{y}}_{2}{\left(\mathit{t}-5\right)}^{2}$,${\mathit{y}}_{2}{\left(\mathit{t}-6\right)}^{2}$, and ${\mathit{y}}_{2}{\left(\mathit{t}-7\right)}^{2}$.

P = polynomialRegressor('y2',4:7,2);

Specify SC as the set of periodic regressors $\mathrm{sin}\left({\mathit{y}}_{1}\left(\mathit{t}-1\right)\right)$, $\mathrm{cos}\left({\mathit{y}}_{1}\left(\mathit{t}-1\right)\right)$, $\mathrm{sin}\left({\mathit{u}}_{1}\left(\mathit{t}-2\right)\right)$, and $\mathrm{cos}\left({\mathit{u}}_{1}\left(\mathit{t}-2\right)\right)$.

SC = periodicRegressor({'y1','u1'},{1,2});

Specify C as the custom regressor $\mathrm{sin}\left({\mathit{y}}_{1}\left(\mathit{t}-1\right){\mathit{u}}_{1}\left(\mathit{t}-2\right)+{\mathit{u}}_{2}\left(\mathit{t}-2\right)\right)$, using the @ symbol to create an anonymous function handle.

C = customRegressor({'y1','u1','u2'},{1 2 2},@(x,y,z)sin(x.*y+z));

Combine the regressors into one regressor set R.

R = [L;P;SC;C]
R =
[4 1] array of linearRegressor, polynomialRegressor, periodicRegressor, customRegressor objects.
------------------------------------
1. Linear regressors in variables y1, u1
Variables: {'y1'  'u1'}
Lags: {[1]  [2 5]}
UseAbsolute: [0 0]
TimeVariable: 't'

------------------------------------
2. Order 2 regressors in variables y2
Order: 2
Variables: {'y2'}
Lags: {[4 5 6 7]}
UseAbsolute: 0
AllowVariableMix: 0
AllowLagMix: 0
TimeVariable: 't'

------------------------------------
3. Periodic regressors in variables y1, u1 with 1 Fourier terms
Variables: {'y1'  'u1'}
Lags: {[1]  [2]}
W: 1
NumTerms: 1
UseSin: 1
UseCos: 1
TimeVariable: 't'
UseAbsolute: [0 0]

------------------------------------
4. Custom regressor: sin(y1(t-1).*u1(t-2)+u2(t-2))
VariablesToRegressorFcn: @(x,y,z)sin(x.*y+z)
Variables: {'y1'  'u1'  'u2'}
Lags: {[1]  [2]  [2]}
Vectorized: 1
TimeVariable: 't'

Regressors described by this set

Create a nonlinear ARX model.

sys = idnlarx({'y1','y2'},{'u1','u2'},R)
sys =
Nonlinear ARX model with 2 outputs and 2 inputs
Inputs: u1, u2
Outputs: y1, y2

Regressors:
1. Linear regressors in variables y1, u1
2. Order 2 regressors in variables y2
3. Periodic regressors in variables y1, u1 with W = 1, and 1 Fourier terms
4. Custom regressor: sin(y1(t-1).*u1(t-2)+u2(t-2))
List of all regressors

Output functions:
Output 1:  Wavelet network with number of units chosen automatically
Output 2:  Wavelet network with number of units chosen automatically

Sample time: 1 seconds

Status:
Created by direct construction or transformation. Not estimated.

Use a linear ARX model instead of a regressor set to construct a nonlinear ARX model.

Construct a linear ARX model using idpoly.

A = [1 -1.2 0.5];
B = [0.8 1];
LinearModel = idpoly(A, B, 'Ts', 0.1);

Specify input and output names for the model using dot notation.

LinearModel.OutputName = 'y1';
LinearModel.InputName = 'u1';

Construct a nonlinear ARX model using the linear ARX model.

m1 = idnlarx(LinearModel)
m1 =
Nonlinear ARX model with 1 output and 1 input
Inputs: u1
Outputs: y1

Regressors:
Linear regressors in variables y1, u1
List of all regressors

Output function: Wavelet network with number of units chosen automatically
Sample time: 0.1 seconds

Status:
Created by direct construction or transformation. Not estimated.

You can create a linear ARX model from any identified discrete-time linear model.

Estimate a second-order state-space model from estimation data z1.

ssModel = ssest(z1,2,'Ts',0.1);

Construct a nonlinear ARX model from ssModel. The software uses the input and output names that ssModel extracts from z1.

m2 = idnlarx(ssModel)
m2 =
Nonlinear ARX model with 1 output and 1 input
Inputs: u1
Outputs: y1

Regressors:
Linear regressors in variables y1, u1
List of all regressors

Output function: Wavelet network with number of units chosen automatically
Sample time: 0.1 seconds

Status:
Created by direct construction or transformation. Not estimated.

Modify regressor assignments by modifying the RegressorUsage table.

Construct a nonlinear ARX model that has two inputs and two outputs.

Create the variable names and the regressors.

varnames = {'y1','y2','u1','u2'};
lags = {[1 2 3],[1 2],[1 2],[1 3]};
reg = linearRegressor(varnames,lags);

Create an output function specification fcn that uses idWaveletNetwork for mapping regressors to output y1 and idSigmoidNetwork for mapping regressors to output y2. Both mapping objects contain linear and nonlinear components.

fcn = [idWaveletNetwork;idSigmoidNetwork];

Construct the nonlinear ARX model.

output_name = {'y1' 'y2'};
input_name = {'u1' 'u2'};
sys = idnlarx(output_name,input_name,reg,fcn)
sys =
Nonlinear ARX model with 2 outputs and 2 inputs
Inputs: u1, u2
Outputs: y1, y2

Regressors:
Linear regressors in variables y1, y2, u1, u2
List of all regressors

Output functions:
Output 1:  Wavelet network with number of units chosen automatically
Output 2:  Sigmoid network with 10 units

Sample time: 1 seconds

Status:
Created by direct construction or transformation. Not estimated.

Display the RegressorUsage table.

disp(sys.RegressorUsage)
y1:LinearFcn    y1:NonlinearFcn    y2:LinearFcn    y2:NonlinearFcn
____________    _______________    ____________    _______________

y1(t-1)       true              true             true              true
y1(t-2)       true              true             true              true
y1(t-3)       true              true             true              true
y2(t-1)       true              true             true              true
y2(t-2)       true              true             true              true
u1(t-1)       true              true             true              true
u1(t-2)       true              true             true              true
u2(t-1)       true              true             true              true
u2(t-3)       true              true             true              true

The rows of the table represent the regressors. The first two columns of the table represent the linear and nonlinear components of the mapping to output y1 (idWaveletNetwork). The last two columns represent the two components of the mapping to output y2 (idSigmoidNetwork).

In this table, all the input and output regressors are inputs to all components.

Remove the y2(t-2) regressor from the y2 nonlinear component.

sys.RegressorUsage{4,4} = false;
disp(sys.RegressorUsage)
y1:LinearFcn    y1:NonlinearFcn    y2:LinearFcn    y2:NonlinearFcn
____________    _______________    ____________    _______________

y1(t-1)       true              true             true              true
y1(t-2)       true              true             true              true
y1(t-3)       true              true             true              true
y2(t-1)       true              true             true              false
y2(t-2)       true              true             true              true
u1(t-1)       true              true             true              true
u1(t-2)       true              true             true              true
u2(t-1)       true              true             true              true
u2(t-3)       true              true             true              true

The table displays false for this regressor-component pair.

Store the regressor names in Names.

Names = sys.RegressorUsage.Properties.RowNames;

Determine the indices of the rows that contain y1 or y2 and set the corresponding values of y1:NonlinearFcn to False.

idx = contains(Names,'y1')|contains(Names,'y2');
sys.RegressorUsage{idx,2} = false;
disp(sys.RegressorUsage)
y1:LinearFcn    y1:NonlinearFcn    y2:LinearFcn    y2:NonlinearFcn
____________    _______________    ____________    _______________

y1(t-1)       true              false            true              true
y1(t-2)       true              false            true              true
y1(t-3)       true              false            true              true
y2(t-1)       true              false            true              false
y2(t-2)       true              false            true              true
u1(t-1)       true              true             true              true
u1(t-2)       true              true             true              true
u2(t-1)       true              true             true              true
u2(t-3)       true              true             true              true

The table values reflect the new assignments.

The RegressorUsage table provides complete flexibility for individually controlling regressor assignments.


text:
# fast math expression parser

28 replies to this topic

### #21phresnel

Member

• Members
• 47 posts

Posted 22 October 2009 - 07:53 PM

.oisyn said:

Nonsense. Naming a header 'stdafx.h' [...]'s nothing unportable about it.
Nitpicky, yes. But only in this case. When code is published that #includes unpublished blackboxes, then
a) (the "mild" form) it might not compile at all
b) (the "evil" form) intended behaviour and actual behaviour might largely vary. Think of #define macros, function overloads, template partial and explicit specializations, et al.

Where is the portability when a) or b) strike?

Quote

In a header, yes. In a sourcefile everybody should decide for himself.

In my opinion, blanket using statements should never exceed function scope. Scope should (imho) be as big as needed, but not bigger.

Quote

All names in de std namespace are defined by the standard.
And as the standard does not define which names may be defined outside "de std namespace", those pulled-in names may very well collide with your code. Sooner or later, with or without tweaking the sourcefile in question.

revision 0:
foo.hh:
#ifndef FOO_HH

#define FOO_HH

#endif
bar.cc:

#include <string>

using namespace std;

#include "foo.hh"

class list {};

int main () {

list frogs;

}

revision 2048:
foo.hh:
#ifndef FOO_HH

#define FOO_HH

#include <list>

#endif

Example consequence (note: bar.cc was never changed anymore!):
main.cc: In function ‘int main()’:

main.cc:10: error: reference to ‘list’ is ambiguous

main.cc:6: error: candidates are: class list

/usr/include/c++/4.3/bits/stl_list.h:416: error:                 template<class _Tp, class _Alloc> class std::list

main.cc:10: error: reference to ‘list’ is ambiguous

main.cc:6: error: candidates are: class list

/usr/include/c++/4.3/bits/stl_list.h:416: error:                 template<class _Tp, class _Alloc> class std::list

main.cc:10: error: expected ;' before ‘frogs’

Quote

Again, nonsense. According to ISO/IEC 14882:2003, paragraph C.2.2.3/1:

Quote

The macro NULL, defined in any of <clocale>, <cstddef>, <cstdio>, <cstdlib>, <cstring>, <ctime>, or <cwchar>, is an implementation-defined C++ null pointer constant in this International Standard (18.1).
int main () {

int *p;

if (NULL == p) {

}

}
main.cc: In function ‘int main()’:

main.cc:3: error: ‘NULL’ was not declared in this scope

I am not sure whether I shall now dive into all my source code files and pull in unrelated #include files just to have NULL defined, or just follow the well established and less redundant convention of using a builtin literal that also happens to be portable.

Quote

Oh, then what is the C++ counterpart of assert()?
The macro assert(). Why?

Anyways, it is good practice to use the C++ counterparts of the C library where available. E.g., math.h defines cos and cosf, whereas cmath only defines the function name cos with three function overloads, thus reducing redundancy, improving readability of template code, helping to avoid the subtle issues when accidentally using 64bit floating point where only 32bit floating point is intended. There are some more less than irrelevant differences.

cassert and assert.h are the same, but why make an exception to the rule for only the assert macro?

~/www/ | picogen.org | metatrace
- --- / .-.. . - / -- -.-- / ... .. --. -. .- - ..- .-. . / .- .--. .--. . .- .-. / --. . . -.- -.--

### #22.oisyn

DevMaster Staff

• Moderators
• 1842 posts

Posted 22 October 2009 - 09:13 PM

phresnel said:

Nitpicky, yes.
No, just wrong. "stdafx.h" is by no means "MSVC++ only"

Quote

In my opinion, blanket using statements should never exceed function scope. Scope should (imho) be as big as needed, but not bigger.
I agree with you on this, but the point is that it is not wrong or evil to do otherwise (as opposed to putting a using directive in a header, which *is* evil). It's just a matter of taste.

Quote

And as the standard does not define which names may be defined outside "de std namespace", those pulled-in names may very well collide with your code. Sooner or later, with or without tweaking the sourcefile in question.
And some think that you shouldn't use those names in the first place to avoid confusion. This is especially true for functions, due to the two phase name lookup in templates.
and obviously I meant "the" std namespace

Quote

int main () {
int *p;
if (NULL == p) {
}
}
main.cc: In function int main():
main.cc:3: error: NULL was not declared in this scope

I am not sure whether I shall now dive into all my source code files and pull in unrelated #include files just to have NULL defined, or just follow the well established and less redundant convention of using a builtin literal that also happens to be portable.
That is besides the point. NULL is not C only. It is just as well C++, and pulling in a header for a language construct is nothing strange (see typeid()). And some think using NULL makes the code more readable. Of course, it has other problems as well (the 0 literal has these as well, but would make these more evident to the programmer), but that will be fixed with nullptr, in which case we will al be using 'nullptr' rather than '0'.

Quote

The macro assert(). Why?
I'm sorry, I misread your comment. I thought you said you didn't need <cassert> as assert() is not C++, but I see now that you meant that you should include <cassert> rather than <assert.h>. Of course I can do nothing other than to agree on that
C++ addict
-
Currently working on: the 3D engine for Tomb Raider.

### #23TheNut

Senior Member

• Moderators
• 1701 posts
• LocationCyberspace

Posted 23 October 2009 - 02:01 AM

Man, you guys need to get out more :lol:
http://www.nutty.ca - Being a nut has its advantages.

### #24phresnel

Member

• Members
• 47 posts

Posted 23 October 2009 - 08:35 AM

.oisyn said:

No, just wrong. "stdafx.h" is by no means "MSVC++ only"

Oops, okay. My intention was more to tell about #including unknown code, rather than to complain about what was MSVC once. Bad wording from my side.

Quote

I agree with you on this, but the point is that it is not wrong or evil to do otherwise (as opposed to putting a using directive in a header, which *is* evil). It's just a matter of taste.
Okay. My taste is to pollute namespaces and scope as sparse as possible. I think it makes my code more "future compatible".

Quote

And some think that you shouldn't use those names in the first place to avoid confusion.
But then the problem is that only the fewest know which words are reserved for the standard (I don't belong to them), and it doesn't help that every decade a plethora of new words are reserved. Especially the upcoming standard will describe a lot of new names, of which are some pretty common in some C++ milieus (e.g. I've seen several different mt19937 in the one or another path tracer implementation; I can only hope they [and me] did not use using namespace, as C++0x describes that name [for kicks, g++-4.4 -std=c++0x, header should be <random>], and many, many others).

Quote

That is besides the point. NULL is not C only. It is just as well C++, and pulling in a header for a language construct is nothing strange (see typeid()). And some think using NULL makes the code more readable. Of course, it has other problems as well (the 0 literal has these as well, but would make these more evident to the programmer), but that will be fixed with nullptr, in which case we will al be using 'nullptr' rather than '0'.
That's right. Though I think 0 vs. pointers is evident enough. I personally consider typeid() and NULL a bit, uhm, dirty, for you must include headers for them (in that respect, I find typeid() even dirtier -> typeid()=first class operator, but "return value" of it needs header :wacko: ). Okay, personal opinion.

TheNut said:

Man, you guys need to get out more
Where, ..., there are people? :ohmy:

joke aside, actually I have a significant other, enjoy pubs, and from time to time go for a walk: http://phresnel.deviantart.com/

~/www/ | picogen.org | metatrace
- --- / .-.. . - / -- -.-- / ... .. --. -. .- - ..- .-. . / .- .--. .--. . .- .-. / --. . . -.- -.--

### #25.oisyn

DevMaster Staff

• Moderators
• 1842 posts

Posted 23 October 2009 - 09:15 AM

TheNut said:

Man, you guys need to get out more

C++ addict
-
Currently working on: the 3D engine for Tomb Raider.

### #26poita

Senior Member

• Members
• 322 posts

Posted 24 October 2009 - 02:41 AM

Cool code, thanks for sharing. Recursive decent parsers are always fun.

Personally, I would change the interface of Parse to be:

const bool Parse(string::iterator first, string::iterator last)

or even better

template <class InputIter>
const bool Parse(InputIter first, InputIter last)`

This interface is more flexible, allowing people to parse substrings, or even lists of chars.

### #27v71

Valued Member

• Members
• 354 posts

Posted 24 October 2009 - 07:32 AM

Thanks for the hint, i am working for adding the ^ operator which i included but not added to the parser, and corrected the code to be more oop compliant, further more i would like to add math functions and the derivatie and integral operator, when its finished i will post it here again.

### #28Luz Reyes

Valued Member

• Members
• 112 posts

Posted 27 August 2010 - 10:08 PM

Oisyn that is hilarious! you are spot on, but sometimes i've been on both sides of that cartoon's computer scree, both correcting ppl and being corrected.

### #29v71

Valued Member

• Members
• 354 posts

Posted 28 August 2010 - 08:58 AM

I just want to point ouy that all those posts on gamedev were posted while i was away and someone used my account, only now taht i have seen this old post again i realized what the sarcasm was...

#### 1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users


text:
(Redirected from Talk:Stadion (unit of length))

## Move

Stadion (unit) was cleared for a move that apparently never happened. That said, per WP:TERSE, there is no need to use the wordier name until someone invents stadion (unit of weight), stadion (unit of pressure), or stadion (unit of boyband marketability). — LlywelynII 02:19, 13 March 2015 (UTC)

## Unit Conversion

I think the article should have a stadion to mile conversion table that works both ways (miles -> stades : stades - > miles) at least for the itinerary stades of 157 m (515 ft) that reads along the lines of this:

-Psychotic Spartan 123

I created my on conversion formula, because I could not find any online. Now I know stades already translate into kilometers (10 litinerary stades = 1.57 km) which means one could just convert from stades to kilometers to miles, but I'd rather take the shorter route. Psychotic Spartan 123 18:07, 24 April 2015 (UTC)

Several objections to this:
• nobody knows how long a stadion was, and the figure you give is just one of many arbitrary values
• we don't include "how-to" content in our articles
• your method is unnecessarily complex: to convert a 515-foot unit to miles, multiply by 515/5280; invert to convert the other way