matlab automotive qas

121
1. How to add noise to an image? The function noise.m, now installed on ashland too, adds Gaussian, uniform, salt and pepper, additive or multiplicative noise to an image. By using the function imnoise we can add noise into an image. The syntax is imnoise( image,type of noise ). 2. What can we use Matlab for? Simple calculations 2. Plotting and analyzing mathematical relationships (2D and 3D) 3. List & Matrix Operations 4. Writing script files (a type of programming) 5. Symbolic manipulation of equations 6. Advanced visualization, animation and GUI interface tools Matlab is to be utilized for data extraction,data analysis and data processing,it is further utilized for some statistical task to analyze the behavior of the system by plotting.it is used to generate stimulus for verification of the system 3. How to call matlab in batch mode? This can be done from the command line or from a makefile. You need a script (filename.m). Just type at the command line, or include in the makefile: matlab<filename.m where filename.m can write to disk a figure, a binary, an ascii file, anything you want. 4. Explain The MATLAB mathematical function library? This is a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms 5. Explain about stress analysis in Matlab? People working on these areas as a aerospace engineers should have familiarity and exposure to NASTRAN and MATLAB with knowledge on space environment and modeling of flexible dynamics. These aerospace engineers will be responsible to conduct stress analysis on metallic and composite structures. NASTRAN, IDEAD, Oracle and PATRAN proficiency level is required. Their duties also include on aircraft which are metallic and composite structures. This includes and understanding of control surface stiffness and loop calculations, finite element modeling (FEM), fatigue testing requirement and analysis.

Upload: rathnampm

Post on 20-Oct-2015

155 views

Category:

Documents


0 download

DESCRIPTION

Matlab Q&A in Automotive Domain

TRANSCRIPT

Page 1: Matlab Automotive QAs

1. How to add noise to an image? 

 

The function noise.m, now installed on ashland too, adds Gaussian, uniform, salt and pepper, 

additive or multiplicative noise to an image. 

 

 

By using the function imnoise we can add noise into an image. The syntax is imnoise( image,type 

of noise ). 

 

2. What can we use Matlab for? 

Simple calculations 2. Plotting and analyzing mathematical relationships (2D and 3D) 3. List & 

Matrix Operations 4. Writing script files (a type of programming) 5. Symbolic manipulation of 

equations 6. Advanced visualization, animation and GUI interface tools 

 

 

Matlab is to be utilized for data extraction,data analysis and data processing,it is further utilized 

for some statistical task to analyze the behavior of the system by plotting.it is used to generate 

stimulus for verification of the system 

3. How to call matlab in batch mode? 

This can be done from the command line or from a makefile. You need a script (filename.m). 

Just type at the command line, or include in the makefile: matlab<filename.m where filename.m 

can write to disk a figure, a binary, an ascii file, anything you want. 

4. Explain The MATLAB mathematical function library? 

This is a vast collection of computational algorithms ranging from elementary functions like sum, 

sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix 

eigenvalues, Bessel functions, and fast Fourier transforms 

5. Explain about stress analysis in Matlab? 

People working on these areas as a aerospace engineers should have familiarity and exposure to 

NASTRAN and MATLAB with knowledge on space environment and modeling of flexible 

dynamics. These aerospace engineers will be responsible to conduct stress analysis on metallic 

and composite structures. NASTRAN, IDEAD, Oracle and PATRAN proficiency level is required. 

Their duties also include on aircraft which are metallic and composite structures. This includes 

and understanding of control surface stiffness and loop calculations, finite element modeling 

(FEM), fatigue testing requirement and analysis. 

Page 2: Matlab Automotive QAs

6. Explain The MATLAB Application Program Interface (API)? 

This is a library that allows you to write C and Fortran programs that interact with MATLAB. It 

include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a 

computational engine, and for reading and writing MAT‐files. 

7. Can MATLAB pass by reference? 

This is really two questions in one. One is "Can I modify a function's input argument?" This would save memory and simplify   programming in some cases. The answer here is "NO". If you modify the input argument of a function, all you do is modify a   copy of the argument local to the function. The only way to modify variables from a function is to return the result when   finished, as in  bigstruct = addelement(bigstruct, 5);  The other question is: "Pass by value wastes memory and time, since copies of variables are made. How can I fix this?" Here,   the answer is "Your assumption is flawed, you don't need to." MATLAB uses a scheme called "copy‐on‐write" to optimize this   sort of thing. Basically, data is shared between variables whenever possible, and a true copy is made only when one of the   variables is modified. So although MATLAB's calling convention appears to be pass‐by‐value, if you don't modify the input   variables, the data is never copied.  

8. How to add noise to an image in Matlab? 

The function noise.m, now installed on ashland too, adds Gaussian, uniform, salt and pepper, 

additive or multiplicative noise to an image. 

9. How can I make MATLAB use the full window width for displaying matrices? 

In R12 (MATLAB 6.0), this can be controlled via a preference. Select the File | Preferences... menu item, and select Command   Window in the Preferences dialog that appears. In the Display section, there's a checkbox labeled Limit matrix display width   

Page 3: Matlab Automotive QAs

to eighty columns. Unchecking that box allows matrix displays to make full use of the Command Window's width. [Unchecked is   the default.]  Starting with MATLAB R12.1, users can access the current command window size using the root property CommandWindowSize. That   is, sz=get(0, 'CommandWindowSize'). In R12.0, there is no way to do this unless you call undocumented C functions from a MEX file.  

10. Why does MATLAB only calculate to 4 significant digits? 

It doesn't. It uses full double‐precision floating point numbers to calculate everything. By default it 

only prints a few decimal places to the screen. You can change this using the command format long. 

Type help format for more information. 

11. How to save default settings across sessions? 

The key is to create a STARTUP.M file. Look at the online help for more detailed instructions specific 

to your operating system. 

12. Can we run Matlab without graphics? 

  Sometimes you may want to run scripts which contain plotting commands without displaying 

the plots and without going into the script to comment out the commands. An example: if you're 

working from home and it's too slow to run graphics over the network. You can play a simple UNIX trick: 

% setenv DISPLAY /dev/null % Matlab. 

13. Explain LaTeX in Matlab? 

Matlab already handles naturally simple LaTeX encodings that allow introducing Greek lettters or 

modifying the font size and appearance in plots. 

14. Explain The MATLAB working environment? 

This is the set of tools and facilities that you work with as the MATLAB user or programmer. It 

includes facilities for managing the variables in your workspace and importing and exporting data. It 

also includes tools for developing, managing, debugging, and profiling M‐files, MATLAB's 

applications. 

15.  On what machines Matlab should be run? 

Run it from sthelens, and only if sthelens is down, from cher, orsay or tiree. It works on other 

machines too, but some of the other machines have older versions of the OS and core dump upon 

exiting from matlab. Some other local machines with new setups work fine. Try your local machine. 

Matlab is blocked from running on the servers 

Page 4: Matlab Automotive QAs

16. LaTeX in Matlab: 

Matlab already handles naturally simple LaTeX encodings that allow introducing Greek lettters or 

modifying the font size and appearance in plots. 

17. What is MATLAB? 

MATLAB is a commercial software package written by The MathWorks, Inc. Quoting from their web page: "Numeric computation, technical graphics and visualization, and an intuitive programming language for applications in engineering and science."  MATLAB is a complete environment for high‐level programming, as well as interactive data analysis. MATLAB excels at numerical computations, especially when dealing with vectors or matrices of data. Symbolic math is available through an add‐on toolbox that uses a Maple kernel.  18. Vectorization What is that ? How to do it ? 

Thinking is terms of full matrices/vectors and also some related functions for that * Use of filter(), 

which works beautifully for some time series models 

19.  How to correctly apply the graphics patches in Matlab? 

Open a LOCAL MACHINE window and type: xhost +ashland # Add the following code sequence just 

before the plot command that was giving you problems: figure; set(gcf,'renderer','zbuffer'); [s,w] = 

unix('echo $DISPLAY'); set(gcf,'XDisplay',w); 

20. What is the FAQ editorial policy? 

This FAQ is actively maintained as a wiki document on MATLAB Central. Currently the MATLAB 

Central File Review Team has accounts that allow them to edit the FAQ. Even though the FAQ is 

hosted at MATLAB Central, content is supplied and maintained by the user community of the 

comp.soft‐sys.matlab newsgroup. For official MATLAB tech support, see instead the MATLAB 

support 

21. Can we run Matlab without graphics? 

Sometimes you may want to run scripts which contain plotting commands without displaying the 

plots and without going into the script to comment out the commands. An example: if you're 

working from home and it's too slow to run graphics over the network. You can play a simple UNIX 

trick: % setenv DISPLAY /dev/null % matlab 

22. How to call matlab in batch mode? 

This can be done from the command line or from a makefile. You need a script (filename.m). Just 

type at the command line, or include in the makefile: matlab<filename.m where filename.m can 

write to disk a figure, a binary, an ascii file, anything you want. 

Page 5: Matlab Automotive QAs

23. On what machines Matlab should be run? 

We will run it from sthelens, and only if sthelens is down, from cher, orsay or tiree. It works on other 

machines too, but some of the other machines have older versions of the OS and core dump upon 

exiting from matlab. Some other local machines with new setups work fine. Try your local machine. 

Matlab is blocked from running on the servers 

24. Vectorization What is that in Matlab? How to do it ? 

Thinking is terms of full matrices/vectors and also some related functions for that * Use of filter(), 

which works beautifully for some time series models 

25. What can we use Matlab for? 

Simple calculations 2. Plotting and analyzing mathematical relationships (2D and 3D) 3. List & Matrix 

Operations 4. Writing script files (a type of programming) 5. Symbolic manipulation of equations 6. 

Advanced visualization, animation and GUI interface tools 

26. How to modify the MATLAB path? 

Easiest solution: use the PATHTOOL GUI. Or if you want command line access: 

Suggested by Joshua Stiff: You can use addpath to add directories from the command line, and 

path2rc to write the current path back to `pathdef.m'. If you do not have write permissions for 

`pathdef.m', path2rc can write to a different file, which you can execute from your `startup.m'. 

27. Explain Handle Graphics in Matlab? 

This is the MATLAB graphics system. It includes high‐level commands for two‐dimensional and 

three‐dimensional data visualization, image processing, animation, and presentation graphics. It also 

includes low‐level commands that allow you to fully customize the appearance of graphics as well as 

to build complete Graphical User Interfaces on your MATLAB applications. 

28. Explain The MATLAB language? 

This is a high‐level matrix/array language with control flow statements, functions, data structures, 

input/output, and object‐oriented programming features. It allows both "programming in the small" 

to rapidly create quick and dirty throw‐away programs, and "programming in the large" to create 

complete large and complex application programs 

29. What are the MATLAB System Parts? 

The MATLAB system consists of five main parts: * The MATLAB language. * The MATLAB working environment. * Handle Graphics. * The MATLAB mathematical function library. 

Page 6: Matlab Automotive QAs

* The MATLAB Application Program Interface (API).   

Page 7: Matlab Automotive QAs

CAN INTERVIEW QUESTIONS:                                                    

1. What is CAN?

Answer: 1. CAN is a multi‐master broadcast serial bus standard for connecting electronic controlunit (ECUs).

2. Controller–area network (CAN or CAN‐bus) is a vehicle bus standard designed to allowmicrocontrollers  a devices to communicate with each other within a vehicle without a host computer.

3. CAN is a message‐based protocol, designed specifically for automotive applications but now alsoused in other areas such as industrial automation and medical equipment.

4. The Controller Area Network (CAN) bus is a serial asynchronous bus used in instrumentationapplications for industries such as automobiles

 2.     CAN frame works?

Answer: SOF – 1 Dominant

Arbitration Field – 11 bit Identifier, 1 bit RTR (or) 11 bit, 1SRR, 1IDE, 18 bit, 1RTR

Control Field – IDE, r0, 4 bits (DLC)

Data Field – (0‐8) Bytes

CRC Field – 15 bits, Delimiter (1 bit recessive)

ACK Field – 1 bit, Delimiter (1 bit recessive)

EOF – 7 bits recessive

IFS – 3 bits recessive

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

1 of 59 8/6/2013 4:17 PM

Page 8: Matlab Automotive QAs

Types of frames – Data, remote, Error frame and Overload frame

Types of errors – ACK error, Bit error, Stuff error, Form error, CRC error

Error frame – 0‐12 superposition flags, 8 recessive (Delimiter)

Overload frame – 0‐12 superposition flags, 8 recessive (Delimiter)

3.     Why CAN is having 120 ohms at each end?

Answer: To minimize the reflection reference, to reduce noise. To ensure that reflection does notcause communication failure, the transmission line must be terminated.

4.     Why CAN is message oriented protocol?

Answer: CAN protocol is a message‐based protocol, not an address based protocol. This means thatmessages are not transmitted from one node to another node based on addresses. Embedded in theCAN message itself is the priority and the contents of the data being transmitted. All nodes in thesystem receive every message transmitted on the bus (and will acknowledge if the message wasproperly received). It is up to each node in the system to decide whether the message received shouldbe immediately discarded or kept to be processed. A single message can be destined for oneparticular node to receive, or many nodes based on the way the network and system are designed.For example, an automotive airbag sensor can be connected via CAN to a safety system router nodeonly. This router node takes in other safety system information and routes it to all other nodes on thesafety system network. Then all the other nodes on the safety system network can receive the latestairbag sensor information from the router at the same time, acknowledge if the message was receivedproperly, and decide whether to utilize this information or discard it.

5.     CAN logic what it follows?

Answer: Wired AND logic

6.     What is CAN Arbitration?

Answer: CAN Arbitration is nothing but the node trying to take control on the CAN bus.

7.     How CAN will follow the Arbitration?

Answer: CSMA/CD + AMP (Arbitration on Message Priority)

Two bus nodes have got a transmission request. The bus access method is CSMA/CD+AMP (CarrierSense Multiple Access with Collision Detection and Arbitration on Message Priority). According tothis algorithm both network nodes wait until the bus is free (Carrier Sense). In that case the bus is freeboth nodes transmit their dominant start bit (Multiple Access). Every bus node reads back bit by bitfrom the bus during the complete message and compares the transmitted value with the receivedvalue. As long as the bits are identical from both transmitters nothing happens. The first time therewas a difference – in this example the 7  bit of the message – the arbitration process takes place:Node A transmits a dominant level, node B transmits a recessive level. The recessive level will beoverwritten by the dominant level. This is detected by node B because the transmitted value is notequal to the received value (Collision Detection). At this point of time node B has lost the arbitration,

th

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

2 of 59 8/6/2013 4:17 PM

Page 9: Matlab Automotive QAs

stops the transmission of any further bit immediately and switches to receive mode, because themessage that has won the arbitration must possibly be processed by this node (Arbitration onMessage Priority)

For example, consider three CAN devices each trying to transmit messages:

•  Device 1 – address 433 (decimal or 00110110001 binary)

•  Device 2 – address 154 (00010011010)•  Device 3 – address 187 (00010111011)

Assuming all three see the bus is idle and begin transmitting at the same time, this is how thearbitration works out. All three devices will drive the bus to a dominant state for the start‐of‐frame(SOF) and the two most significant bits of each message identifier. Each device will monitor the busand determine success. When they write bit 8 of the message ID, the device writing message ID 433will notice that the bus is in the dominant state when it was trying to let it be recessive, so it willassume a collision and give up for now. The remaining devices will continue writing bits until bit 5,then the device writing message ID 187 will notice a collision and abort transmission. This leaves thedevice writing message ID 154 remaining. It will continue writing bits on the bus until complete or anerror is detected. Notice that this method of arbitration will always cause the lowest numerical valuemessage ID to have priority. This same method of bit‐wise arbitration and prioritization applies to the18‐bit extension in the extended format as well.

8.     What is the speed of CAN?

Answer: 40m @1Mbps and if the cable length increases will decrease the speed, due to RLC on thecable.

 9.     If master sends 764 and Slave sends 744 which will get the arbitration?

Answer: Starts from MSB, first nibble is same, Master sends 7, slaves also sends 7 the message withmore dominant bits will gain the arbitration, lowest the message identifier higher the priority.

10.   Standard CAN and Extended CAN difference?

Answer: Number of identifiers can be accommodated for standard frame are 2power11.

 Number of identifiers more compare to base frame, for extended frame are 2power29.

IDE bit – 1 for extended frame.

IDE bit – 0 for Standard frame.

11.   What is bit stuffing?

Answer: CAN uses a Non‐Return‐to‐Zero protocol, NRZ‐5, with bit stuffing. The idea behind bitstuffing is to provide a guaranteed edge on the signal so the receiver can resynchronize with thetransmitter before minor clock discrepancies between the two nodes can cause a problem. WithNRZ‐5 the transmitter transmits at most five consecutive bits with the same value. After five bits withthe same value (zero or one), the transmitter inserts a stuff bit with the opposite state.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

3 of 59 8/6/2013 4:17 PM

Page 10: Matlab Automotive QAs

12. What is the use of bit stuffing?

Answer: Long NRZ messages cause problems in receivers

• Clock drift means that if there are no edges, receivers lose track of bits

• Periodic edges allow receiver to resynchronize to sender clock

13.     What are the functions of CAN transceiver?

Answer: The transceiver provides differential transmit capability to the bus and differential receivecapability to the CAN controller. Transceiver provides an advanced interface between the protocolcontroller and the physical bus in a Controller Area Network (CAN) node.

Typically, each node in a CAN system must have a device to convert the digital signals generated bya CAN controller to signals suitable for transmission over the bus cabling (differential output). It alsoprovides a buffer between the CAN controller and the high‐voltage spikes that can be generated onthe CAN bus by outside sources (EMI, ESD, electrical transients, etc.).

The can transceiver is a device which detects the signal levels that are used on the CAN bus to thelogical signal levels recognized by a microcontroller.

14.     Functionality of Data link layer in CAN?

Answer: LLC (Logical Link Control) – Overload control, notification, Message filtering and Recoverymanagement functions.

MAC (Medium Access Control) ‐ Encapsulation/ de‐capsulation, error detection and control, stuffingand de‐stuffing and serialization/de‐serialization.

15.     What is meant by synchronization?

Answer: Synchronization is timekeeping which requires the coordination of events to operate asystem in unison.

16.     What is meant by Hard synchronization and soft synchronization?

Answer: Hard Synchronization to be performed at every edge from recessive‐to‐dominant edgeduring Bus Idle. Additionally, Hard Synchronization is required for each received SOF bit. An SOFbit can be received both during Bus Idle, and also during Suspend Transmission and at the end ofInterframe Space. Any node disables Hard Synchronization if it samples an edge from recessive todominant or if it starts to send the dominant SOF bit.

Two types of synchronization are supported:

– Hard synchronization is done with a falling edge on the bus while the bus is idle, which is

interpreted as a Start of frame (SOF). It restarts the internal Bit Time Logic.

– Soft synchronization is used to lengthen or shorten a bit time while a CAN frame is received.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

4 of 59 8/6/2013 4:17 PM

Page 11: Matlab Automotive QAs

17.     What is the difference between function and physical addressing?

Answer: Functional addressing is an addressing scheme that labels messages based upon theiroperation code or content. Physical addressing is an addressing scheme that labels messages basedupon the physical address location of their source and/or destination(s).

18.     What happens if I have to send more than 8‐bytes of data?

Answer: The J1939 standard has defined a method of communicating more than 8 bytes of data bysending the data in packets as specified in the Transport Protocol (TP). There are two types of TP, onefor broadcasting the data, and the other for sending it to a specific address.

DTC consists of 4 components – SPN, FMI, OC and CM.

A DTC is a combination of four independent fields: the Suspect Parameter Number (SPN) of thechannel or feature that can have faults; a Failure Mode Identifier (FMI) of the specific fault; theoccurrence count (OC) of the SPN/FMI combination; and the SPN conversion method (CM) whichtells the receiving mode how to interpret the SPN. Together, the SPN, FMI, OC and CM form anumber that a diagnostic tool can use to understand the failure that is being reported.

 (http://automotivetechis.files.wordpress.com/2012/06/clip_image002.jpg)

Figure 1 – Message format

19.     What is KWP2000?

Answer:  KWP 2000(ISO14230) is a Diagnostic communications standard. Specifies possible systemconfigurations using the K & L lines. As 9141‐2 but limited to the physical characteristics. Specifiespossible system configurations using the K & L lines.

5 Baud wake up as 9141‐ 2New fast initialisation method

20.     What is OBDII?

Answer:  On‐Board Diagnostics in an automotive context is a generic term referring to a vehicle’sself‐diagnostic and reporting capability

21.     Why Diagnostic Standards?

Answer:  As systems got more complex the link between cause and symptom became less obvious.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

5 of 59 8/6/2013 4:17 PM

Page 12: Matlab Automotive QAs

This meant that electronic systems had to have some level of self diagnosis and to communicate to theoutside world. Initially many systems used their own protocols which meant that garages had tohave a large number of tools – even to diagnose a single vehicle.

 22.     What is meant by verification and validation??

Answer: Verification and Validation (V&V) is the process of checking that a software system meetsspecifications and that it fulfills its intended purpose. It is normally part of the software testingprocess of a project.

According to the Capability Maturity Model (CMMI‐SW v1.1),

Verification: The process of evaluating software to determine whether the products of a givendevelopment phase satisfy the conditions imposed at the start of that phase.Validation: The process of evaluating software during or at the end of the development process todetermine whether it satisfies specified requirements.Verification shows conformance with specification; validation shows that the program meets thecustomer’s needs

 23.  Can you have two transmitters using the same exact header field?

Answer:  No – that would produce a bus conflict

• Unless you have middleware that ensures only one node can transmit at a time

– For example use a low priority message as a token to emulate token‐passing

24.   CAN physical layer voltage levels

(http://automotivetechis.files.wordpress.com/2012/06/can1.jpg)

25. CAN bit timing:

According to the CAN specification, the bit time is divided into four segments. The SynchronizationSegment, the Propagation Time Segment, the Phase Buffer Segment 1, and the Phase Buffer Segment

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

6 of 59 8/6/2013 4:17 PM

Page 13: Matlab Automotive QAs

2. Each segment consists of a specific, programmable number of time quanta (see Table 1). The lengthof the time quantum (tq), which is the basic time unit of the bit time, is defined by the CANcontroller’s system clock fsys and the Baud Rate Prescaler (BRP) :tq = BRP / fsys. Typical systemclocks are : fsys = fosc or fsys = fosc/2.

The Synchronization Segment Sync_Seg is that part of the bit time where edges of the CAN bus levelare expected to occur; the distance between an edge that occurs outside of Sync_Seg and the Sync_Segis called the phase error of that edge. The Propagation Time Segment Prop_Seg is intended tocompensate for the physical delay times within the CAN network. The Phase Buffer SegmentsPhase_Seg1 and Phase_Seg2 surround the Sample Point. The (Re‐)Synchronization Jump Width (SJW)defines how far a resynchronization may move the Sample Point inside the limits defined by thePhase Buffer Segments to compensate for edge phase errors.

 

(http://automotivetechis.files.wordpress.com/2012/06/untitle436d.jpg)

Two types of synchronization exist : Hard Synchronization and Resynchronization. A HardSynchronization is done once at the start of a frame; inside a frame only Resynchronizations occur.

• Hard Synchronization After a hard synchronization, the bit time is restarted with the end of

Sync_Seg, regardless of the edge phase error. Thus hard synchronization forces the edge which hascaused the hard synchronization to lie within the synchronization segment of the restarted bit time.

• Bit Resynchronization Resynchronization leads to a shortening or lengthening of the bit time such

that the position of the sample point is shifted with regard to the edge.

26. Formula for Baudrate calculation?

 The baud rate is calculated as:

baud rate (bits per second) = 18.432 x 10^6 / BRP / (1 + TSEG1 + TSEG2)

27. What happen when two CAN nodes are sending same identifier at a same time?

Two nodes on the network are not allowed to send messages with the same id. If two nodes try tosend a message with the same id at the same time arbitration will not work. Instead, one of thetransmitting nodes will detect that his message is distorted outside of the arbitration field. The nodes

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

7 of 59 8/6/2013 4:17 PM

Page 14: Matlab Automotive QAs

will then use the error handling of CAN, which in this case ultimately will lead to one of thetransmitting node being switched off (bus‐off mode).

28. what is the difference between Bit Rate and Baud Rate?

 The difference between Bit and Baud rate is complicated and intertwining. Both are dependent and

inter‐related. But the simplest explanation is that a Bit Rate is how many data bits are transmitted persecond. A baud Rate is the number of times per second a signal in a communications channelchanges.Bit rates measure the number of data bits (that is 0′s and 1′s) transmitted in one second in acommunication channel. A figure of 2400 bits per second means 2400 zeros or ones can be transmittedin one second, hence the abbreviation “bps.” Individual characters (for example letters or numbers)that are also referred to as bytes are composed of several bits.A baud rate is the number of times asignal in a communications channel changes state or varies. For example, a 2400 baud rate means thatthe channel can change states up to 2400 times per second. The term “change state” means that it canchange from 0 to 1 or from 1 to 0 up to X (in this case, 2400) times per second. It also refers to theactual state of the connection, such as voltage, frequency, or phase level).The main difference betweenthe two is that one change of state can transmit one bit, orslightly more or less than one bit, that depends on themodulation technique used. So the bit rate (bps) and baudrate (baud per second) have this connection:bps = baud persecond x the number of bit per baudThe modulationtechnique determines the number of bit per baud. Here aretwo examples:When FSK (Frequency Shift Keying, atransmission technique) is used, each baud transmits onebit. Only one change in state is required to send a bit. Thus,the modem’s bps rate is equal to the baud rate. When abaud rate of 2400 is used, a modulation technique calledphase modulation that transmits four bits per baud is used.So:2400 baud x 4 bits per baud = 9600 bpsSuch modems are capable of 9600 bps operation.C Interview Questions :1.     What is the difference between declaration and definition?

Answer: Definition means where a variable or function is defined in reality and actual memory isallocated for variable or function.

Declaration means just giving a reference of a variable and function.

2.     What are the different storage classes in C?

Answer: AUTO, STATIC, EXTERN, REGISTER

auto is the default storage class for local variables.

{

int Count;

auto int Month;

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

8 of 59 8/6/2013 4:17 PM

Page 15: Matlab Automotive QAs

}

register is used to define local variables that should be stored in a register instead of RAM Thismeans that the variable has a maximum size equal to the register size (usually one word) and cannothave the unary ‘&’ operator applied to it (as it does not have a memory location).

                    {

                      register int  Miles;

                    }

Register should only be used for variables that require quick access – such as counters. It should alsobe noted that defining ‘register’ goes not mean that the variable will be stored in a register. It meansthat it MIGHT be stored in a register – depending on hardware and implementation restrictions.

static – Storage Class

static is the default storage class for global variables. The two variables below (count and road) bothhave a static storage class.

     static int Count;int Road;main(){printf(“%d\n”, Count);printf(“%d\n”, Road);}

‘static’ can also be defined within a function. If this is done, the variable is initalized at compilationtime and retains its value between calls. Because it is initialized at compilation time, the initializationvalue must be a constant. This is serious stuff – tread with care.

     void Func(void){static Count=1;}

Here is an example

There is one very important use for ‘static’. Consider this bit of code.

     char *Func(void);main(){char *Text1;Text1 = Func();}char *Func(void){char Text2[10]=”martin”;

return(Text2);}

‘Func’ returns a pointer to the memory location where ‘Text2′ starts BUT Text2 has a storage classof auto and will disappear when we exit the function and could be overwritten by something else.The answer is to specify:

     static char Text[10]=”martin”;

The storage assigned to ‘Text2′ will remain reserved for the duration if the program.

extern – storage Class

extern defines a global variable that is visable to ALL object modules. When you use ‘extern’ thevariable cannot be initalized as all it does is point the variable name at a storage location that hasbeen previously defined.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

9 of 59 8/6/2013 4:17 PM

Page 16: Matlab Automotive QAs

Source 1                                                                 Source 2

——–                                                                     ——–

extern int count;                                                     int count=5;

write()                                                                           main()

{                                                                                      {

printf(“count is %d\n”, count);                                   write();

}                                                                                       }

Count in ‘source 1′ will have a value of 5. If source 1 changes the value of count – source 2 will see thenew value. Here are some example source files.

 3.     What is interrupt?

 Answer: Interrupts (also known as traps or exceptions in some processors) are a technique of

diverting the processor from the execution of the current program so that it may deal with someevent that has occurred. Such an event may be an error from a peripheral, or simply that an I/Odevice has finished the last task it was given and is now ready for another. An interrupt is generatedin your computer every time you type a key or move the mouse. You can think of it as a hardware‐generated function call.

 4.     What is Hardware Interrupt?

Answer: There are two ways of telling when an I/O device (such as a serial controller or a diskcontroller) is ready for the next sequence of data to be transferred. The first is busy waiting or polling,where the processor continuously checks the device’s status register until the device is ready. Thiswastes the processor’s time but is the simplest to implement. For some time‐critical applications,polling can reduce the time it takes for the processor to respond to a change of state in a peripheral.

5.  What is Software Interrupt?

Answer: A software interrupt is generated by an instruction. It is the lowest‐priority interrupt and isgenerally used by programs to request a service to be performed by the system software (operatingsystem or firmware).

Difference between Hardware Interrupt and Software Interrupt

An interrupt is a special signal that causes the computer’s central processing unit to suspend what itis doing and transfers its control to a special program called an interrupt handler. The responsibilityof an interrupt handler is to determine what caused the interrupt, service the interrupt and thenreturn the control to the point from where the interrupt was caused. The differencebetween hardware interrupt and software interrupt is as below:

Hardware Interrupt: This interrupt is caused by some external device such as request to start an I/O

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

10 of 59 8/6/2013 4:17 PM

Page 17: Matlab Automotive QAs

or occurrence of a hardware failure.

Software Interrupt: This interrupt can be invoked with the help of INT instruction. A programmertriggered this event that immediately stops execution of the program and passes execution over to theINT handler. The INT handler is usually a part of the operating system and determines the action tobe taken e.g. output to the screen, execute file etc.

Thus a software interrupt as it’s name suggests is driven by a software instruction and a hardwareinterrupt is the result of external causes.

6. What is Interrupt latency? How do you measure interrupt latency? How to reduce the interruptlatency?

Answer: Interrupt latency is the time between interrupt request and execution of first instruction ofthe ISR.

We need a oscilloscope or a logic state analyzer. By entering the interrupt service routine (ISR), youneed to activate an available port on your hardware (like a led port or so on) and deactivate it justbefore returning from the ISR. You can do that by writing the appropriate code.

By connecting one input of the oscilloscope (or logic state analyzer) to the INTR pin of themicroprocessor and the second one to the port you activate/deactivate, you can measure the latencytime and the duration of the ISR

Causes of interrupt latencies

 The first delay is typically in the hardware: The interrupt request signal needs to be synchronized

to the CPU clock. Depending on the synchronization logic, typically up to 3 CPU cycles can be lostbefore the interrupt request has reached the CPU core. The CPU will typically complete the current instruction. This instruction can take a lot of cycles;

on most systems, divide, push‐multiple or memory‐copy instructions are the instructions whichrequire most clock cycles. On top of the cycles required by the CPU, there are in most casesadditional cycles required for memory access. In an ARM7 system, the instruction STMDBSP!,{R0‐R11,LR}; Push parameters and perm. Registers is typically the worst case instruction. Itstores 13 32‐bit registers on the stack. The CPU requires 15 clock cycles. The memory system mayrequire additional cycles for wait states.After completion of the current instruction, the CPU performs a mode switch or pushes registers(typically PC and flag registers) on the stack. In general, modern CPUs (such as ARM) perform amode switch, which requires less CPU cycles than saving registers.Pipeline fill: Most modern CPUs are pipelined. Execution of an instruction happens in variousstages of the pipeline. An instruction is executed when it has reached its final stage of the pipeline.Since the mode switch has flushed the pipeline, a few extra cycles are required to refill thepipeline.

7.  Vonneuman and harvard architecture differences?

Answer: The name Harvard Architecture comes from the Harvard Mark I relay‐based computer. Themost obvious characteristic of the Harvard Architecture is that it has physically separate signals andstorage for code and data memory. It is possible to access program memory and data memory

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

11 of 59 8/6/2013 4:17 PM

Page 18: Matlab Automotive QAs

simultaneously. Typically, code (or program) memory is read‐only and data memory is read‐write.Therefore, it is impossible for program contents to be modified by the program itself.

The vonneumann Architecture is named after the mathematician and early computer scientist Johnvon Neumann. von Neumann machines have shared signals and memory for code and data. Thus,the program can be easily modified by itself since it is stored in read‐write memory.

Harvard architecture has separate data and instruction busses, allowing transfers to be performedsimultaneously on both buses. Von Neumann architecture has only one bus which is used for bothdata transfers and instruction fetches, and therefore data transfers and instruction fetches must bescheduled – they cannot be performed at the same time.

It is possible to have two separate memory systems for a Harvard architecture. As long as data andinstructions can be fed in at the same time, then it doesn’t matter whether it comes from a cache ormemory. But there are problems with this. Compilers generally embed data (literal pools) within thecode, and it is often also necessary to be able to write to the instruction memory space, for example inthe case of self modifying code, or, if an ARM debugger is used, to set software breakpoints inmemory. If there are two completely separate, isolated memory systems, this is not possible. Theremust be some kind of bridge between the memory systems to allow this.

Using a simple, unified memory system together with a Harvard architecture is highly inefficient.Unless it is possible to feed data into both buses at the same time, it might be better to use a vonNeumann architecture processor.

Use of caches

At higher clock speeds, caches are useful as the memory speed is proportionally slower. Harvardarchitectures tend to be targeted at higher performance systems, and so caches are nearly alwaysused in such systems.

Von Neumann architectures usually have a single unified cache, which stores both instructions anddata. The proportion of each in the cache is variable, which may be a good thing. It would in principlebe possible to have separate instruction and data caches, storing data and instructions separately.This probably would not be very useful as it would only be possible to ever access one cache at atime.

Caches for Harvard architectures are very useful. Such a system would have separate caches for eachbus. Trying to use a shared cache on a Harvard architecture would be very inefficient since then onlyone bus can be fed at a time. Having two caches means it is possible to feed both busessimultaneously….exactly what is necessary for a Harvard architecture.

This also allows to have a very simple unified memory system, using the same address space for bothinstructions and data. This gets around the problem of literal pools and self modifying code. What itdoes mean, however, is that when starting with empty caches, it is necessary to fetch instructions anddata from the single memory system, at the same time. Obviously, two memory accesses are neededtherefore before the core has all the data needed. This performance will be no better than a vonNeumann architecture. However, as the caches fill up, it is much more likely that the instruction ordata value has already been cached, and so only one of the two has to be fetched from memory. Theother can be supplied directly from the cache with no additional delay. The best performance is

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

12 of 59 8/6/2013 4:17 PM

Page 19: Matlab Automotive QAs

achieved when both instructions and data are supplied by the caches, with no need to access externalmemory at all.

This is the most sensible compromise and the architecture used by ARMs Harvard processor cores.Two separate memory systems can perform better, but would be difficult to implement

8.     RISC and CISC differences?

Answer:

CISC: (Complex Instruction Set Computer)

Eg: Intel and AMD CPU’s

CISC chips have a large amount of different and complex instructions.CISC chips are relatively slow (compared to RISC chips) per instruction, but use little (less thanRISC) instructions.CISC architecture is to complete a task in as few lines of assembly as possible. This is achieved bybuilding processor hardware that is capable of understanding and executing a series ofoperations.In CISC, compiler has to do very little work to translate a high‐level language statement intoassembly. Because the length of the code is relatively short, very little RAM is required to storeinstructions. The emphasis is put on building complex instructions directly into the hardware.When executed, this instruction loads the two values into separate registers, multiplies theoperands in the execution unit, and then stores the product in the appropriate register.

RISC: (Reduced Instruction Set Computer)

Eg: Apple, ARM processors

Fewer, simpler and faster instructions would be better, than the large, complex and slower CISCinstructions. However, more instructions are needed to accomplish a task.RISC chips require fewer transistors, which makes them easier to design and cheaper to produce.it’s easier to write powerful optimized compilers, since fewer instructions exist.RISC is cheaper and faster.RISC puts a greater burden on the software. Software needs to become more complex. Softwaredevelopers need to write more lines for the same tasks. Therefore they argue that RISC is not thearchitecture of the future, since conventional CISC chips are becoming faster and cheaperSimple instructions that can be executed within one clock cycle.“MULT” command described above could be divided into three separate commands: “LOAD,”which moves data from the memory bank to a register, “PROD,” which finds the product of twooperands located within the registers, and “STORE,” which moves data from a register to thememory banks.At first, this may seem like a much less efficient way of completing the operation. Because thereare more lines of code, more RAM is needed to store the assembly level instructions. The compilermust also perform more work to convert a high‐level language statement into code of this form.Separating the “LOAD” and “STORE” instructions actually reduces the amount of work that thecomputer must perform.Major problem of RISC – they don’t afford the widespread compatibility, that x86 chips do.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

13 of 59 8/6/2013 4:17 PM

Page 20: Matlab Automotive QAs

        CISC RISC

Emphasis on hardware Emphasis on software

Includes multi‐clockcomplex instructions

Single‐clock,reduced instruction only

Memory‐to‐memory:“LOAD” and “STORE”incorporated in instructions

Register to register:“LOAD” and “STORE”are independent instructions

Small code sizes,high cycles per second

Low cycles per second,large code sizes

Transistors used for storingcomplex instructions

Spends more transistorson memory registers

CISC RISC

Complex instructions require multiple cycles Reduced instructions take 1cycle

Many instructions can reference memory Only Load and Storeinstructions can referencememory

Instructions are executed one at a time Uses pipelining to executeinstructions

Few general registers Many general registers

9.     What are the startup code steps?

Answer:

Disable all the interrupts.1.

Copy and initialized data from ROM to RAM.2.

Zero the uninitialized data area.3.

Allocate space and for initialize the stack.4.

Initialize the processor stack pointer5.

Call main6.

10.     What are the booting steps for a CPU?

Answer:

The power supply does a self check and sends a power‐good signal to the CPU.

The CPU starts executing the code stored in ROM on the motherboard starts the address 0xFFFF0.

The routines in ROM test the central hardware, search for video ROM, perform a checksum on thevideo ROM and executes the routines in video ROM.The routines in the mother board ROM then continue searching for any ROM, checksum and

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

14 of 59 8/6/2013 4:17 PM

Page 21: Matlab Automotive QAs

executes these routines.After performing the POST (Power On‐Self Test) is executed. The system will search for a bootdevice.Assuming that the valid boot device is found, IO.SYS is loaded into memory and executed. IO.SYSconsists primarily of initialization code and extension to the memory board ROM BIOS.MSDOS.SYS is loaded into memory and executed. MSDOS.SYS contains the DOS routines.CONFIG.SYS (created and modified by the user. load additional device drivers for peripheraldevices), COMMAND.COM (It is command interpreter‐ It translates the commands entered bythe user. It also contains internal DOS commands. It executes and AUTOEXEC.BAT),AUTOEXEC.BAT (It contains all the commands that the user wants which are executedautomatically every time the computed is started).

11. What Little‐Endian and Big‐Endian? How can I determine whether a machine’s byte order isbig‐endian or little endian? How can we convert from one to another?

 First of all, Do you know what Little‐Endian and Big‐Endian mean?

Little Endian means that the lower order byte of the number is stored in memory at the lowestaddress, and the higher order byte is stored at the highest address. That is, the little end comes first.For example, a 4 byte, 32‐bit integerByte3 Byte2 Byte1 Byte0will be arranged in memory asfollows:Base_Address+0 Byte0Base_Address+1 Byte1Base_Address+2 Byte2Base_Address+3 Byte3Intel processors use “Little Endian” byte order.”Big Endian” means that thehigher order byte of the number is stored in memory at the lowest address, and the lower order byteat the highest address. The big end comes first.Base_Address+0 Byte3Base_Address+1 Byte2Base_Address+2 Byte1Base_Address+3 Byte0Motorola, Solaris processors use “Big Endian” byte order.In “Little Endian”form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way for all formats.They first pick up the lowest order byte at offset 0 and proceed from there. Also, because of the 1:1relationship between address offset and byte number (offset 0 is byte 0), multiple precisionmathematic routines are easy to code. In “Big Endian” form, since the high‐order byte comes first, thecode can test whether the number is positive or negative by looking at the byte at offset zero. Its notrequired to know how long the number is, nor does the code have to skip over any bytes to find thebyte containing the sign information. The numbers are also stored in the order in which they areprinted out, so binary to decimal routines are particularly efficient. Here is some code to determinewhat is the type of your machine.int num = 1;if(*(char *)&num == 1){printf(“\nLittle‐Endian\n”);}else{printf(“Big‐Endian\n”);}And here is some code to convert from one Endian to another.int myreversefunc(int num){int byte0, byte1, byte2, byte3;byte0 = (num & x000000FF) >> 0 ;

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

15 of 59 8/6/2013 4:17 PM

Page 22: Matlab Automotive QAs

byte1 = (num & x0000FF00) >> 8 ;byte2 = (num & x00FF0000) >> 16 ;byte3 = (num & xFF000000) >> 24 ;return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));}12. Program to find if a machine is big endian or little endian?

01 #include "stdio.h" 

02 #define BIG_ENDIAN 0 

03 #define LITTLE_ENDIAN 1 

04 int main() 

05 {

06     int value; 

07     value = endian(); 

08     if (value == 1) 

09     printf("Machine is little endian\n",value); 

10     else

11     printf("Machine is Big Endian\n",value); 

12 }

13 int endian() { 

14 short int word = 0x0001; 

15 char *byte = (char *) &word; 

16 return (byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN); 

17 }

13. Swap 2 variables without using temporary variable!a = a + bb = a – ba = a – b14. Write a program to generate the Fibonacci Series?#include<stdio.h>#include<conio.h>main(){int n,i,c,a=0,b=1;printf(“Enter Fibonacci series of nth term : “);scanf(“%d”,&n);printf(“%d %d “,a,b);for(i=0;i<=(n‐3);i++){

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

16 of 59 8/6/2013 4:17 PM

Page 23: Matlab Automotive QAs

c=a+b;a=b;b=c;printf(“%d “,c);}getch();}Output :Enter Fibonacci series of nth term : 70 1 1 2 3 5 8  15. Write a program to find unique numbers in an array?Answer:for (i=1;i<=array.length;i++) {found=false;for (k=i+1;k<=array.length;k++) {if (array[i]==array[k]) found=true;}if (!found) println(array[i]);}16. Write a C program to print Equilateral Triangle using numbers?

01 /* C program to print Equilateral Triangle*/

02 #include<stdio.h>

03 main()

04 {

05       int i,j,k,n; 

06  

07       printf("Enter number of rows  of the triangle \n"); 

08       scanf("%d",&n); 

09  

10       for(i=1;i<=n;i++) 

11       { 

12               for(j=1;j<=n‐i;j++) 

13               { 

14                       printf(" "); 

15               } 

16               for(k=1;k<=(2*i)‐1;k++) 

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

17 of 59 8/6/2013 4:17 PM

Page 24: Matlab Automotive QAs

17               { 

18                       printf("i"); 

19               } 

20               printf("\n"); 

21       } 

22       getch();

 17. Write a program for deletion and insertion of a node in single linked list?

#include<stdio.h>#include<stdlib.h>typedef struct Node{int data;struct Node *next;}node;void insert(node *pointer, int data){/* Iterate through the list till we encounter the last node.*/while(pointer‐>next!=NULL){pointer = pointer ‐> next;}/* Allocate memory for the new node and put data in it.*/pointer‐>next = (node *)malloc(sizeof(node));pointer = pointer‐>next;pointer‐>data = data;pointer‐>next = NULL;}int find(node *pointer, int key){pointer =  pointer ‐> next; //First node is dummy node./* Iterate through the entire linked list and search for the key. */while(pointer!=NULL){if(pointer‐>data == key) //key is found.{return 1;}pointer = pointer ‐> next;//Search in the next node.}/*Key is not found */return 0;}

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

18 of 59 8/6/2013 4:17 PM

Page 25: Matlab Automotive QAs

void delete(node *pointer, int data){/* Go to the node for which the node next to it has to be deleted */while(pointer‐>next!=NULL && (pointer‐>next)‐>data != data){pointer = pointer ‐> next;}if(pointer‐>next==NULL){printf(“Element %d is not present in the list\n”,data);return;}/* Now pointer points to a node and the node next to it has to be removed */node *temp;temp = pointer ‐> next;/*temp points to the node which has to be removed*/pointer‐>next = temp‐>next;/*We removed the node which is next to the pointer (which is also temp) */free(temp);/* Beacuse we deleted the node, we no longer require the memory used for it .free() will deallocate the memory.*/return;}void print(node *pointer){if(pointer==NULL){return;}printf(“%d “,pointer‐>data);print(pointer‐>next);}int main(){/* start always points to the first node of the linked list.temp is used to point to the last node of the linked list.*/node *start,*temp;start = (node *)malloc(sizeof(node));temp = start;temp ‐> next = NULL;/* Here in this code, we take the first node as a dummy node.The first node does not contain data, but it used because to avoid handling special casesin insert and delete functions.*/printf(“1. Insert\n”);printf(“2. Delete\n”);printf(“3. Print\n”);

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

19 of 59 8/6/2013 4:17 PM

Page 26: Matlab Automotive QAs

printf(“4. Find\n”);while(1){int query;scanf(“%d”,&query);if(query==1){int data;scanf(“%d”,&data);insert(start,data);}else if(query==2){int data;scanf(“%d”,&data);delete(start,data);}else if(query==3){printf(“The list is “);print(start‐>next);printf(“\n”);}else if(query==4){int data;scanf(“%d”,&data);int status = find(start,data);if(status){printf(“Element Found\n”);}else{printf(“Element Not Found\n”);                        }}}}18. Can a variable be both const and volatile? Yes. The const modifier means that this code cannotchange the value of the variable, but that does not mean that the value cannot be changed by meansoutside this code. For instance, in the example in  FAQ 8, the timer structure was accessed through avolatile const pointer. The function itself did not change the value of the timer, so it was declaredconst. However, the value was changed by hardware on the computer, so it was declared volatile. If avariable is both const and volatile, the two modifiers can appear in either order. 19. what are Constant and Volatile Qualifiers?

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

20 of 59 8/6/2013 4:17 PM

Page 27: Matlab Automotive QAs

constis used with a datatype declaration or definition to specify an unchanging value

Examples:

const int five = 5;

const double pi = 3.141593;

constobjects may not be changed

The following are illegal:

const int five = 5;

const double pi = 3.141593;

pi = 3.2;

five = 6;

volatilespecifies a variable whose value may be changed by processes outside the current

programOne example of a volatileobject might be a buffer used to exchange data with an external

device:

int

check_iobuf(void)

{

volatile int iobuf;

int val;

while (iobuf == 0) {

}

val = iobuf;

iobuf = 0;

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

21 of 59 8/6/2013 4:17 PM

Page 28: Matlab Automotive QAs

return(val);

}

if iobuf had not been declared volatile, the compiler would notice that nothing happens inside

the loop and thus eliminate the loop

const and volatile can be used together

An input‐only buffer for an external device could be declared as const

volatile (or volatile const, order is not important) to make sure the compiler knows that

the variable should not be changed (because it is input‐only) and that its value may be alteredby processes other than the current program

 The keywords const and volatile can be applied to any declaration, including those of structures,

unions, enumerated types or typedef names. Applying them to a declaration is called qualifying the

declaration—that’s why const and volatile are called type qualifiers, rather than type specifiers. Hereare a few representative examples:

volatile i;

volatile int j;

const long q;

const volatile unsigned long int rt_clk;

struct{

        const long int li;

        signed char sc;

}volatile vs;

Don’t be put off; some of them are deliberately complicated: what they mean will be explained later.Remember that they could also be further complicated by introducing storage class specifications aswell! In fact, the truly spectacular

extern const volatile unsigned long int rt_clk;

is a strong possibility in some real‐time operating system kernels.

Let’s look at what is meant when const is used. It’s really quite simple: const means that something

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

22 of 59 8/6/2013 4:17 PM

Page 29: Matlab Automotive QAs

is not modifiable, so a data object that is declared with const as a part of its type specification must

not be assigned to in any way during the run of a program. It is very likely that the definition of theobject will contain an initializer (otherwise, since you can’t assign to it, how would it ever get avalue?), but this is not always the case. For example, if you were accessing a hardware port at a fixedmemory address and promised only to read from it, then it would be declared to be const but not

initialized.

Taking the address of a data object of a type which isn’t const and putting it into a pointer to

the const‐qualified version of the same type is both safe and explicitly permitted; you will be able to

use the pointer to inspect the object, but not modify it. Putting the address of a const type into apointer to the unqualified type is much more dangerous and consequently prohibited (although youcan get around this by using a cast). Here is an example:

#include <stdio.h>

#include <stdlib.h>

main(){

        int i;

        const int ci = 123;

        /* declare a pointer to a const.. */

        const int *cpi;

        /* ordinary pointer to a non‐const */

        int *ncpi;

        cpi = &ci;

        ncpi = &i;

        /*

         * this is allowed

         */

        cpi = ncpi;

        /*

         * this needs a cast

         * because it is usually a big mistake,

         * see what it permits below.

         */

        ncpi = (int *)cpi;

        /*

         * now to get undefined behaviour...

         * modify a const through a pointer

         */

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

23 of 59 8/6/2013 4:17 PM

Page 30: Matlab Automotive QAs

        *ncpi = 0;

        exit(EXIT_SUCCESS);

}

Example 8.3

As the example shows, it is possible to take the address of a constant object, generate a pointer to anon‐constant, then use the new pointer. This is an error in your program and results in undefinedbehaviour.

The main intention of introducing const objects was to allow them to be put into read‐only store, andto permit compilers to do extra consistency checking in a program. Unless you defeat the intent bydoing naughty things with pointers, a compiler is able to check that const objects are not modified

explicitly by the user.

An interesting extra feature pops up now. What does this mean?

char c;

char *const cp = &c;

It’s simple really; cp is a pointer to a char, which is exactly what it would be if the const weren’t

there. The const means that cp is not to be modified, although whatever it points to can be—the

pointer is constant, not the thing that it points to. The other way round is

const char *cp;

which means that now cp is an ordinary, modifiable pointer, but the thing that it points to must notbe modified. So, depending on what you choose to do, both the pointer and the thing it points to maybe modifiable or not; just choose the appropriate declaration.

After const, we treat volatile. The reason for having this type qualifier is mainly to do with the

problems that are encountered in real‐time or embedded systems programming using C. Imaginethat you are writing code that controls a hardware device by placing appropriate values in hardwareregisters at known absolute addresses.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

24 of 59 8/6/2013 4:17 PM

Page 31: Matlab Automotive QAs

Let’s imagine that the device has two registers, each 16 bits long, at ascending memory addresses; thefirst one is the control and status register (csr) and the second is a data port. The traditional way ofaccessing such a device is like this:

/* Standard C example but without const or volatile */

/*

* Declare the device registers

* Whether to use int or short

* is implementation dependent

*/

struct devregs{

        unsigned short  csr;    /* control & status */

        unsigned short  data;   /* data port */

};

/* bit patterns in the csr */

#define ERROR   0x1

#define READY   0x2

#define RESET   0x4

/* absolute address of the device */

#define DEVADDR ((struct devregs *)0xffff0004)

/* number of such devices in system */

#define NDEVS   4

/*

* Busy‐wait function to read a byte from device n.

* check range of device number.

* Wait until READY or ERROR

* if no error, read byte, return it

* otherwise reset error, return 0xffff

*/

unsigned int read_dev(unsigned devno){

        struct devregs *dvp = DEVADDR + devno;

        if(devno >= NDEVS)

                return(0xffff);

        while((dvp‐>csr & (READY | ERROR)) == 0)

                ; /* NULL ‐ wait till done */

        if(dvp‐>csr & ERROR){

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

25 of 59 8/6/2013 4:17 PM

Page 32: Matlab Automotive QAs

                dvp‐>csr = RESET;

                return(0xffff);

        }

        return((dvp‐>data) & 0xff);

}

Example 8.4

The technique of using a structure declaration to describe the device register layout and names isvery common practice. Notice that there aren’t actually any objects of that type defined, so thedeclaration simply indicates the structure without using up any store.

To access the device registers, an appropriately cast constant is used as if it were pointing to such astructure, but of course it points to memory addresses instead.

However, a major problem with previous C compilers would be in the while loop which tests thestatus register and waits for the ERROR or READY bit to come on. Any self‐respecting optimizing

compiler would notice that the loop tests the same memory address over and over again. It wouldalmost certainly arrange to reference memory once only, and copy the value into a hardware register,thus speeding up the loop. This is, of course, exactly what we don’t want; this is one of the few placeswhere we must look at the place where the pointer points, every time around the loop.

Because of this problem, most C compilers have been unable to make that sort of optimization in thepast. To remove the problem (and other similar ones to do with when to write to where a pointerpoints), the keyword volatile was introduced. It tells the compiler that the object is subject to

sudden change for reasons which cannot be predicted from a study of the program itself, and forcesevery reference to such an object to be a genuine reference.

Here is how you would rewrite the example, making use of const and volatile to get what you

want.

/*

* Declare the device registers

* Whether to use int or short

* is implementation dependent

*/

struct devregs{

        unsigned short volatile csr;

        unsigned short const volatile data;

};

/* bit patterns in the csr */

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

26 of 59 8/6/2013 4:17 PM

Page 33: Matlab Automotive QAs

#define ERROR   0x1

#define READY   0x2

#define RESET   0x4

/* absolute address of the device */

#define DEVADDR ((struct devregs *)0xffff0004)

/* number of such devices in system */

#define NDEVS   4

/*

* Busy‐wait function to read a byte from device n.

* check range of device number.

* Wait until READY or ERROR

* if no error, read byte, return it

* otherwise reset error, return 0xffff

*/

unsigned int read_dev(unsigned devno){

        struct devregs * const dvp = DEVADDR + devno;

        if(devno >= NDEVS)

                return(0xffff);

        while((dvp‐>csr & (READY | ERROR)) == 0)

                ; /* NULL ‐ wait till done */

        if(dvp‐>csr & ERROR){

                dvp‐>csr = RESET;

                return(0xffff);

        }

        return((dvp‐>data) & 0xff);

}

Example 8.5

The rules about mixing volatile and regular types resemble those for const. A pointer to

a volatile object can be assigned the address of a regular object with safety, but it is dangerous (and

needs a cast) to take the address of a volatile object and put it into a pointer to a regular object.

Using such a derived pointer results in undefined behaviour.

If an array, union or structure is declared with const or volatile attributes, then all of the members

take on that attribute too. This makes sense when you think about it—how could a member ofa const structure be modifiable?

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

27 of 59 8/6/2013 4:17 PM

Page 34: Matlab Automotive QAs

That means that an alternative rewrite of the last example would be possible. Instead of declaring thedevice registers to be volatile in the structure, the pointer could have been declared to point to

a volatile structure instead, like this:

struct devregs{

      unsigned short  csr;    /* control & status */

      unsigned short  data;   /* data port */

};

volatile struct devregs *const dvp=DEVADDR+devno;

Since dvp points to a volatile object, it not permitted to optimize references through the pointer.

Our feeling is that, although this would work, it is bad style. The volatile declaration belongs in the

structure: it is the device registers which are volatile and that is where the information should be

kept; it reinforces the fact for a human reader.

So, for any object likely to be subject to modification either by hardware or asynchronous interruptservice routines, the volatile type qualifier is important.

Now, just when you thought that you understood all that, here comes the final twist. A declarationlike this:

volatile struct devregs{

      /* stuff */

}v_decl;

declares the type struct devregs and also a volatile‐qualified object of that type, called v_decl.

A later declaration like this

struct devregs nv_decl;

declares nv_decl which is not qualified with volatile! The qualification is not part of the type

of struct devregs but applies only to the declaration of v_decl. Look at it this way round, which

perhaps makes the situation more clear (the two declarations are the same in their effect):

struct devregs{

      /* stuff */

}volatile v_decl;

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

28 of 59 8/6/2013 4:17 PM

Page 35: Matlab Automotive QAs

If you do want to get a shorthand way of attaching a qualifier to another type, you canuse typedef to do it:

struct x{

      int a;

};

typedef const struct x csx;

csx const_sx;

struct x non_const_sx = {1};

const_sx = non_const_sx;        /* error ‐ attempt to modify a const */

20.What are the differences between a union and a structure in C?

A union is a way of providing an alternate way of describing the same memory area. In this way, youcould have a struct that contains a union, so that the “static”, or similar portion of the data isdescribed first, and the portion that changes is described by the union. The idea of a union could behandled in a different way by having 2 different structs defined, and making a pointer to each kind ofstruct. The pointer to struct “a” could be assigned to the value of a buffer, and the pointer to struct“b” could be assigned to the same buffer, but now a‐>some field and b‐>some otherfield are bothlocated in the same buffer. That is the idea behind a union. It gives different ways to break down thesame buffer area.The difference between structure and union are: 1. union allocates the memory equal to themaximum memory required by the member of the union but structure allocates the memory equal tothe total memory required by the members. 2. In union, one block is used by all the member of theunion but in case of structure, each member have their own memory space

Difference Between Stucture and Union :

Structure Union

i. Access Members

We can access all the members of structure atanytime.

Only one member of union can be accessed atanytime.

ii. Memory Allocation

Memory is allocated for all variables. Allocates memory for variable which variablerequire more memory.

iii. Initialization

All members of structure can be initialized Only the first member of a union can beinitialized.

iv. Keyword

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

29 of 59 8/6/2013 4:17 PM

Page 36: Matlab Automotive QAs

‘struct’ keyword is used to declare structure. ‘union’ keyword is used to declare union.

v. Syntax

struct struct_name

{

    structure element 1;

    structure element 2;

‐‐‐‐‐‐‐‐‐‐

‐‐‐‐‐‐‐‐‐‐

    structure element n;

}struct_var_nm;

union union_name

{

    union element 1;

    union element 2;

‐‐‐‐‐‐‐‐‐‐

‐‐‐‐‐‐‐‐‐‐

    union element n;

}union_var_nm;

vi. Example

struct item_mst

{

    int rno;

    char nm[50];

}it;

union item_mst

{

    int rno;

    char nm[50];

}it;

While structure enables us treat a number of different variables stored at different in memory , aunion enables us to treat the same space in memory as a number of different variables. That is aUnion offers a way for a section of memory to be treated as a variable of one type on one occasionand as a different variable of a different type on another occasion.There is frequent requirement while interacting with hardware to access access a byte or group ofbytes simultaneously and sometimes each byte individually. Usually union is the answer.=======Difference With example=======

Lets say a structure containing an int,char and float is created and a union containing int char floatare declared.

struct TT{ int a; float b; char c; } Union UU{ int a; float b; char c; }sizeof TT(struct) would be >9 bytes (compiler dependent‐if int,float, char are taken as 4,4,1)sizeof UU(Union) would be 4 bytes as supposed from above.If a variable in double exists in unionthen the size of union and struct would be 8 bytes and cumulative size of all variables in struct.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

30 of 59 8/6/2013 4:17 PM

Page 37: Matlab Automotive QAs

struct foo{char c;long l;char *p;};

union bar{char c;long l;char *p;};

A struct foo contains all of the elements c, l, and p. Each element is separate and distinct.

A union bar contains only one of the elements c, l, and p at any given time. Each element is stored inthe same memory location (well, they allstart at the same memory location), and you can only refer to the element which was last stored. (ie:after “barptr‐>c = 2;” you cannot referenceany of the other elements, such as “barptr‐>p” without invoking undefined behavior.)

Try the following program. (Yes, I know it invokes the above‐mentioned “undefined behavior”, butmost likely will give some sort of output on most computers.)

==========

#include

struct foo{char c;long l;char *p;};

union bar{char c;long l;char *p;};

int main(int argc,char *argv[])

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

31 of 59 8/6/2013 4:17 PM

Page 38: Matlab Automotive QAs

{struct foo myfoo;union bar mybar;

myfoo.c = 1;myfoo.l = 2L;myfoo.p = “This is myfoo”;

mybar.c = 1;mybar.l = 2L;mybar.p = “This is mybar”;

printf(“myfoo: %d %ld %s\n”,myfoo.c,myfoo.l,myfoo.p);printf(“mybar: %d %ld %s\n”,mybar.c,mybar.l,mybar.p);

return 0;}

==========

On my system, I get:

myfoo: 1 2 This is myfoomybar: 100 4197476 This is mybar==========credit to original author.

Structure: Structure is a combination elements, which can be predefined data types or other structure.The length/size of the structure is the sum of the length of its elements.In C, structures cannot contain functions. in C++ it can.

Union: Union is a combination elements, which can be predefined data types or other union . But, thesize/length of union is the maximum of internal elements.

the sizeof() operator returns the size slightly more than calculated size due to padding, which againdepends on OS== Answer == Union allocates the memory equal to the maximum memory required by the memberof the union but structure allocates the memory equal to the total memory required by the members.In union,one block is used by all the member of the union but in case of structure, each member havetheir own memory space.

21. What is meant by structure padding?

Answer: compilers pad structures to optimize data transfers. This is an hardware architecture issue.Most modern CPUs perform best when fundamental types, like ‘int’ or ‘float’, are aligned on memoryboundaries of a particular size (eg. often a 4byte word on 32bit archs). Many architectures don’t allowmisaligned access or if they do inoccur a performance penality. When a compiler processes astructure declaration it will add extra bytes between fields to meet alignment needs.

Most processors require specific memory alignment on variables certain types. Normally the

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

32 of 59 8/6/2013 4:17 PM

Page 39: Matlab Automotive QAs

minimum alignment is the size of the basic type in question, for instance this is common

char variables can be byte aligned and appear at any byte boundary

short (2 byte) variables must be 2 byte aligned, they can appear at any even byte boundary. Thismeans that 0×10004567 is not a valid location for a short variable but 0×10004566 is.

long (4 byte) variables must be 4 byte aligned, they can only appear at byte boundaries that are amultiple of 4 bytes. This means that 0×10004566 is not a valid location for a long variable but0×10004568 is.

Structure padding occurs because the members of the structure must appear at the correct byteboundary, to achieve this the compiler puts in padding bytes (or bits if bit fields are in use) so that thestructure members appear in the correct location. Additionally the size of the structure must be suchthat in an array of the structures all the structures are correctly aligned in memory so there may bepadding bytes at the end of the structure too

struct example {char c1;short s1;char c2;long l1;char c3;}

In this structure, assuming the alignment scheme I have previously stated then

c1 can appear at any byte boundary, however s1 must appear at a 2 byte boundary so there is apadding byte between c1 and s1.

c2 can then appear in the available memory location, however l1 must be at a 4 byte boundary sothere are 3 padding bytes between c2 and l1

c3 then appear in the available memory location, however because the structure contains a longmember the structure must be 4 byte aligned and must be a multiple of 4 bytes in size. Thereforethere are 3 padding bytes at the end of the structure. It would appear in memory in this order

c1padding bytes1 byte 1s1 byte 2c2padding bytepadding bytepadding bytel1 byte 1l1 byte 2l1 byte 3l1 byte 4c3

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

33 of 59 8/6/2013 4:17 PM

Page 40: Matlab Automotive QAs

padding bytepadding bytepadding byte

The structure would be 16 bytes long.

re‐written like this

struct example {long l1;short s1;char c1;char c2;char c3;}

Then l1 appears at the correct byte alignment, s1 will be correctly aligned so no need for paddingbetween l1 and s1. c1, c2, c3 can appear at any location. The structure must be a multiple of 4 bytes insize since it contains a long so 3 padding bytes appear after c3It appears in memory in the order

l1 byte 1l1 byte 2l1 byte 3l1 byte 4s1 byte 1s1 byte 2c1c2c3padding bytepadding bytepadding byte

and is only 12 bytes long.

I should point out that structure packing is platform and compiler (and in some cases compilerswitch) dependent.

Memory Pools are just a section of memory reserved for allocating temporarily to other parts of theapplication

A memory leak occurs when you allocate some memory from the heap (or a pool) and then delete allreferences to that memory without returning it to the pool it was allocated from.

Program:

struct  MyStructA {   char a;

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

34 of 59 8/6/2013 4:17 PM

Page 41: Matlab Automotive QAs

   char b;

   int    c;

};

struct MyStructB {   char a;

   int    c;

   char b;

};

int main(void) {        int sizeA = sizeof(struct MyStructA);

        int sizeB = sizeof(struct MyStructB);

        printf(“A = %d\n”, sizeA);

        printf(“B = %d\n”, sizeB);

        return 0;

}

22. What is the difference between macro and constant variables in C?

Macros are replaced by preprocessor, but in constant data type will be checked by compiler. Macrosare replaced without checking the values sometimes the programmer want to change values only in asingle function at that prefer to use constant than a macro.

The first technique comes from the C programming language. Constants may be defined using thepreprocessor directive, #define The preprocessor is a program that modifies your source file prior tocompilation. Common preprocessor directives are #include, which is used toinclude additional code into your source file, #define, which is used to define a constant and#if/#endif, which can be used to conditionally determine which parts of your code will be compiled.The #define directive is used as follows.

#define pi 3.1415#define id_no 12345

Wherever the constant appears in your source file, the preprocessor replaces it by its value. So, forinstance, every “pi” in your source code will be replace by 3.1415. The compiler will only see thevalue 3.1415 in your code, not “pi”. The problem with this technique is that the replacement is donelexically, without any type checking, without any bound checking and without any scope checking.Every “pi” is just replaced by its value. The technique is outdated, exists to support legacy code andshould be avoided.ConstThe second technique is to use the keyword const when defining a variable. When used the compilerwill catch attempts to modify variables that have been declared const.

const float pi = 3.1415;const int id_no = 12345;

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

35 of 59 8/6/2013 4:17 PM

Page 42: Matlab Automotive QAs

There are two main advantages over the first technique.

First, the type of the constant is defined. “pi” is float. “id_no” is int. This allows some type checkingby the compiler.&nbs p;Second, these constants are variables with a definite scope. The scope of a variable relates to parts ofyour program in which it is defined. Some variables may exist only in certain functions or in certainblocks of code.

Ex : You may want to use “id_no” in one functionand a completely unrelated “id_no” in your main program.

23.  What is difference between re‐entrant function and recursive function in C?

Answer: Re entrant function is a function which guaranteed that which can be work well under multithreaded environment. mean while function is access by one thread, another thread can call it meanthere is separate execution stack and handling for each. So function should not contain any static orshared variable which can harm or disturb the execution. Mean function which can be called bythread, while running from another thread safely and properly

Example:

int t;

void swap(int *x, int *y)

{

 int s;

 s = t; // save global variable

 t = *x;

 *x = *y;

 // hardware interrupt might invoke isr() here!

 *y = t;

 t = s; // restore global variable

}

void isr()

{

 int x = 1, y = 2;

 swap(&x, &y);

}

Recursive function Example:

void doll ( int size ){if ( size == 0 )   // No doll can be smaller than 1 atom (10^0==1) so doesn’t call itself

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

36 of 59 8/6/2013 4:17 PM

Page 43: Matlab Automotive QAs

return;          // Return does not have to return something, it can be used//  to exit a functiondoll ( size – 1 ); // Decrements the size variable so the next doll will be smaller.}int main(){doll ( 10 ); //Starts off with a large doll (it’s a logarithmic scale)

24. What is V‐Model ? What are the benefits?

The V‐model represents a software development process (also applicable to hardware development)which may be considered an extension of the waterfall model. Instead of moving down in a linearway, the process steps are bent upwards after the coding phase, to form the typical V shape. TheV‐Model demonstrates the relationships between each phase of the development life cycle and itsassociated phase of testing.

The V model has a number of benefits:

1. Systems development projects usually have a test approach, or test strategy document, whichdefines how testing will be performed throughout the lifecycle of the project. The V model provides aconsistent basis and standard for part of that strategy.

2.  The V model explicitly suggests that testing (quality assurance) should be considered early on inthe life of a project. Testing and fixing can be done at any stage in the lifecycle. However, the cost offinding and fixing faults increases dramatically as development progresses. Evidence suggests that ifa fault uncovered during design costs 1.0 monetary unit to correct, then the same fault uncovered justbefore testing will cost 6.5 units, during testing 15 units, and after release between 60 and 100 units.The need to find faults as soon as possible reinforces the need for the quality assurance of documentssuch as the requirements specification and the functional specification. This is performed using statictesting techniques such as inspections and walkthroughs.

3.  It introduces the idea of specifying test requirements and expected outcomes prior to performingthe actual tests. For example, the acceptance tests are performed against a specification ofrequirements, rather than against some criteria dreamed up when the acceptance stage has beenreached

4. The V model provides a focus for defining the testing that must take place within each stage. Thedefinition of testing is assisted by the idea of entry and exit criteria. Hence, the model can be used todefine the state a deliverable must be in before it can enter and leave each stage. The exit criteria ofone stage are usually the entry criteria of the next. In many organizations, there is concern about thequality of the program code released by individual programmers. Some programmers release codethat appears to be fault‐free, while others release code that still has many faults in it. The problem ofprogrammers releasing code with different levels of robustness would be addressed in the exitcriteria of unit design and unit testing. Unit design would require programmers to specify theirintended test cases before they wrote any program code. Coding could not begin until these test caseshad been agreed with an appropriate manager. Second, the test cases would have to be conductedsuccessfully before the program could leave the unit test stage and be released to integration testing.

5. Finally, the V model provides a basis for defining who is responsible for performing the testing at

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

37 of 59 8/6/2013 4:17 PM

Page 44: Matlab Automotive QAs

each stage. Here are some typical responsibilities:

acceptance testing performed by userssystem testing performed by system testersintegration testing performed by program team leadersunit testing performed by programmers.

The V model is therefore an excellent basis for the partitioning of testing, highlighting the fact that allthe participants in the development of a system have a responsibility for quality assurance andtesting.

25. What is meant by Black box testing and white box testing?

White‐box testing (also known as clear box testing, glass box testing, transparent box testing,and structural testing) is a method of testing software that tests internal structures or workings of anapplication, as opposed to its functionality (i.e. black‐box testing). In white‐box testing an internalperspective of the system, as well as programming skills, are used to design test cases. The testerchooses inputs to exercise paths through the code and determine the appropriate outputs. This isanalogous to testing nodes in a circuit, e.g. in‐circuit testing (ICT).

While white‐box testing can be applied at the unit, integration and system levels of the softwaretesting process, it is usually done at the unit level. It can test paths within a unit, paths between unitsduring integration, and between subsystems during a system–level test. Though this method of testdesign can uncover many errors or problems, it might not detect unimplemented parts of thespecification or missing requirement.

Black‐box testing is a method of software testing that tests the functionality of an application asopposed to its internal structures or workings (see white‐box testing). This method of test can beapplied to all levels of software testing: unit, integration, system and acceptance. It typicallycomprises most if not all testing at higher levels, but can also dominate unit testing as well.

 (http://en.wikipedia.org/wiki/File:Blackbox.svg)White Box Testing: Means testing the application with coding /programming knowledge. Thatmeans the tester has to correct the code also.

Black box testing: Testing the application without coding /programming knowledge that means thetester doesn’t require coding knowledge. Just he examines the application external functionalbehaviour and GUI features.

Sl.No Black Box White Box

1 Focuses on the functionality of thesystem

Focuses on the structure (Program) ofthe system

2 Techniques used are :

Equivalence partitioningBoundary‐value analysisError guessing

Techniques used are:

Basis Path TestingFlow Graph NotationControl Structure Testing

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

38 of 59 8/6/2013 4:17 PM

Page 45: Matlab Automotive QAs

Race conditionsCause‐effect graphingSyntax testingState transition testingGraph matrix

1.      Condition Testing

2.      Data Flow testing

Loop Testing

1.      Simple Loops

2.      Nested Loops

3.      Concatenated Loops

4.      Unstructured Loops

3 Tester can be non technical Tester should be technical

4 Helps to identify the vagueness andcontradiction in functionalspecifications

Helps to identify the logical andcoding issues.

26. What are the types of testings?

unit testing

Component testing

Integration testing

System testing

27. The Difference between Bit Rate and Baud Rate?

The difference between Bit and Baud rate is complicated and intertwining. Both are dependent andinter‐related. But the simplest explanation is that a Bit Rate is how many data bits are transmitted persecond. A baud Rate is the number of times per second a signal in a communications channelchanges.

Bit rates measure the number of data bits (that is 0′s and 1′s) transmitted in one second in acommunication channel. A figure of 2400 bits per second means 2400 zeros or ones can be transmittedin one second, hence the abbreviation “bps.” Individual characters (for example letters or numbers)that are also referred to as bytes are composed of several bits.

A baud rate is the number of times a signal in a communications channel changes state or varies. Forexample, a 2400 baud rate means that the channel can change states up to 2400 times per second. Theterm “change state” means that it can change from 0 to 1 or from 1 to 0 up to X (in this case, 2400)times per second. It also refers to the actual state of the connection, such as voltage, frequency, orphase level).

The main difference between the two is that one change of state can transmit one bit, or slightly moreor less than one bit, that depends on the modulation technique used. So the bit rate (bps) and baudrate (baud per second) have this connection:

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

39 of 59 8/6/2013 4:17 PM

Page 46: Matlab Automotive QAs

bps = baud per second x the number of bit per baud

The modulation technique determines the number of bit per baud. Here are two examples:

When FSK (Frequency Shift Keying, a transmission technique) is used, each baud transmits one bit.Only one change in state is required to send a bit. Thus, the modem’s bps rate is equal to the baudrate. When a baud rate of 2400 is used, a modulation technique called phase modulation thattransmits four bits per baud is used. So:

2400 baud x 4 bits per baud = 9600 bps

Such modems are capable of 9600 bps operation.

3)Difference between flash and EEprom

Similarities1.

Both flash and EEPROM are digital storage methods used by computers and other devices. Bothare non‐volatile ROM technologies to which you can write and from which you can erase multipletimes.

Differences

The primary difference between flash and EEPROM is the way they erase data. While EEPROMdestroys the individual bytes of memory used to store data, flash devices can only erase memoryin larger blocks. This makes flash devices faster at rewriting, as they can affect large portions ofmemory at once. Since a rewrite may affect unused blocks of data, it also adds unnecessarily tousage of the device, shortening its lifespan in comparison with EEPROM.

Usage

Flash storage is commonly used in USB memory drives and solid state hard drives. EEPROM isused in a variety of devices, from programmable VCRs to CD players.

28. Can structures be passed to the functions by value?

Ans: yes structures can be passed by value. But unnecessary memory wastage.

29. Why cannot arrays be passed by values to functions?Ans : When a array is passed to a function, the array is internally changed to a μpointer. And pointersare always passed by reference.30. What is meant by static functions?Ans: static functions are functions that are only visible to other functions in the same fileExample:

main.c

   #include <STDIO.H>

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

40 of 59 8/6/2013 4:17 PM

Page 47: Matlab Automotive QAs

   main()

   {

     Func1();   

     Func2();

   }

funcs.c

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

    *

    * Function declarations (prototypes).

    *

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

   /* Func1 is only visable to functions in this file. */   

   static void Func1(void);

   /* Func2 is visable to all functions. */

   void Func2(void); 

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

    *

    * Function definitions

    *

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

   void Func1(void)

   {

     puts("Func1 called");

   }

   /*************************************/   void Func2(void)        

   {

     puts("Func2 called");

   }

31. Difference between declaration, definition & initialization?

Ans: A declaration introduces a name – an identifier – to the compiler. It tells the compiler “Thisfunction or this variable exists somewhere, and here is what it should look like.”

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

41 of 59 8/6/2013 4:17 PM

Page 48: Matlab Automotive QAs

A definition, on the other hand, says: “Make this variable here” or “Make this function here.” Itallocates storage for the name. This meaning works whetheryou’re talking about a variable or a function; in either case, at the point of definition the compilerallocates storage.

extern const int x = 1; /* Initialization */This initialization establishes this as a definition, not a declaration.

extern const int x; /* Declaration */This declaration in C++ means that the definition exists elsewhere.

32. What is the difference between pass by value by reference in c and pass by reference in c?Pass By Reference :In Pass by reference address of the variable is passed to a function. Whatever changes made to the formalparameter will affect to the actual parameters‐ Same memory location is used for both variables.(Formal and Actual)‐‐ it is useful when you required to return more then 1 valuesPass By Value:‐ In this method value of the variable is passed. Changes made to formal will not affect the actual parameters.‐ Different memory locations will be created for both variables.‐ Here there will be temporary variable created in the function stack which does not affect the original variable.

 33. What is the difference between flash memory, EPROM and EEPROM?

EEPROM is an older, more reliable technology. It is somewhat slower than Flash. Flash and EEPROMare very similar, but there is a subtle difference. Flash and EEPROM both use quantum cells to trapelectons. Each cell represents one bit of data. The presence – or absence – of electons in a cell indicateswhether the bit is a 1 or 0.The cells have a finite life – every time a cell is erased, it wears out a littlebit. In EEPROM, cells are erased one‐by‐one. The only cells erased are those which are 1 but need tobe zero. (Writing a 1 to a cell that’s 0 causes very little wear, IIRC)In Flash, a large block is erased allat once. In some devices, this “block” is the entire device. So in flash, cells are erased whether theyneed it or not. This cuts down on the lifespan of the device, but is much, much faster than theEEPROM method of going cell‐by‐cell.Erasure method: Both Flash and EEPROM erase cells by means of an electric field. I think it ishigh‐frequency and “pops” the electrons out of the Other similar devices are EPROM (sometimesUVEPROM) and OTPROM (sometimes PROM). EPROM/UVEPROM lacks the structures thatgenerate the electrical field for erasure. These devices have a window on top, usually covered by apaper sticker. To erase, the sticker is removed and the device is exposed to intense ultraviolet light for30‐45 minutes. The only difference between OTPROM and UVEPROM is that OTPROM lacks the UVwindow – there is no way to erase the data. Adding the UV window to the device packagesignificantly increases cost, so there is a niche for one‐time‐programmable devices

The information stored in an EPROM chip can be erased by exposing the chip to strong UV light.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

42 of 59 8/6/2013 4:17 PM

Page 49: Matlab Automotive QAs

EPROM chips are easily recognized by the small quartz window used for erasure. Once erased thechip can be re‐programmed.

EPROM is more expensive to buy per unit cost, but can prove cheaper in the long run for someapplications. For example if PROM was used for firmware that needed upgraded every 6 months orso – it could prove quite expensive buying new chips!

This has the added advantage that the information stored can be re‐written in blocks and hence canbe used to store system settings that the user may want to change periodically.

This solid state memory has considerably reduced in price over recent years and is nowadayscommonly used to store system settings such as BIOS settings

34. What is difference between Volatile & Non Volatile Memory?

Volatile memory

Volatile memory is computer memory that requires power to maintain the stored information. Mostmodern semiconductor volatile memory is either Static RAM (see SRAM) or dynamic RAM (seeDRAM). SRAM retains its contents as long as the power is connected and is easy to interface to butuses six transistors per bit. Dynamic RAM is more complicated to interface to and control and needsregular refresh cycles to prevent its contents being lost. However, DRAM uses only one transistor anda capacitor per bit, allowing it to reach much higher densities and, with more bits on a memory chip,be much cheaper per bit. SRAM is not worthwhile for desktop system memory, where DRAMdominates, but is used for their cache memories. SRAM is commonplace in small embedded systems,which might only need tens of kilobytes or less. Forthcoming volatile memory technologies that hopeto replace or compete with SRAM and DRAM include Z‐RAM, TTRAM, A‐RAM and ETA RAM.

Non‐volatile memory is computer memory that can retain the stored information even when notpowered. Examples of non‐volatile memory include read‐only memory (see ROM), flash memory,most types of magnetic computer storage devices (e.g. hard disks, floppy discs and magnetic tape),optical discs, and early computer storage methods such as paper tape and punched cards.Forthcoming non‐volatile memory technologies include FeRAM, CBRAM, PRAM, SONOS, RRAM,Racetrack memory, NRAM and Millipede.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

43 of 59 8/6/2013 4:17 PM

Page 50: Matlab Automotive QAs

35. What is a reentrant function?

A reentrant function is a function which can be safely executed concurrently. This means it shouldallow a re‐entry while it is running. The reentrant function should work only on the data given by thecalling function. It must not have any static data also.The term “reentrant” is used to refer to side wall profiles of the nozzles, wherein exit diameters of thenozzles are smaller than entrance diameters of the nozzles so that the side walls of the nozzles are notperpendicular to a plane defined by an exit surface of the nozzle member.

A Reentrant function is a function which guaranteed that which can be work well under multithreaded environment. Mean while function is access by one thread, another thread can call it…mean there is separate execution stack and handling for each. So function should not contain anystatic or shared variable which can harm or disturb the execution.

36. Why we are using UDS, If CAN support diagnostics communication?

In CAN it will support internal diagnostic messages. UDS & KWP2000 are used for to test withexternal tester and to know the type of problem

37.  How to recover from CAN‐ Busoff?

To distinguish between temporary and permanent failures every CAN bus controller has two ErrorCounters: The REC (Receive Error Counter) and the TEC (Transmit Error Counter). The counters areincremented upon detected errors respectively are decremented upon correct transmissions orreceptions. Depending on the counter values the state of the node is changed: The initial state of aCAN bus controller is Error Active that means the controller can send active Error Flags. Thecontroller gets in the Error Passive state if there is an accumulation of errors.

On CAN bus controller failure or an extreme accumulation of errors there is a state transition to BusOff. The controller is disconnected from the bus by setting it in a state of high‐resistance. The Bus Offstate should only be left by a software reset. After software reset the CAN bus controller has towait for 128 x 11 recessive bits to transmit a frame. This is because other nodes may pendingtransmission requests. It is recommended not to start an hardware reset because the wait time rulewill not be followed then.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

44 of 59 8/6/2013 4:17 PM

Page 51: Matlab Automotive QAs

37. What is Virtual functional bus?

Virtual function bus can be described as a system modeling and communication concept. It is logicalentity that facilitates theconcept of relocatability within the AUTOSAR software architecture by providing a virtualinfrastructure that is independent from any actual underlying infrastructure and provides all servicesrequired for a virtual interaction between AUTOSAR components.

38. Intra and Inter ECU communication?

Intra‐ECU which denotes the communication between two software components residing on thesame ECU and Inter‐ECU which denotes the situation when two software components reside ondifferent ECU’s that are connected via a bus network.

39. What is the difference between global and static global variables?Global variables are variables defined outside of any function. Their scope starts at the point wherethey are defined and lasts to the end of the file. They have external linkage, which means that in othersource files, the same name refers to the same location in memory.Static global variables are private to the source file where they are defined and do not conflict withother variables in other source files which would have the same name.

40. How to access a Global variables in other files?

Variables declared outside of a block are called global variables. Global variables have programscope, which means they can be accessed everywhere in the program, and they are only destroyedwhen the program ends.

Here is an example of declaring a global variable:

12345678910

int g_nX; // global variable

 

int main()

{

    int nY; // local variable nY

 

    // global vars can be seen everywhere in program 

    // so we can change their values here

    g_nX = 5;

} // nY is destroyed here

Because global variables have program scope, they can be used across multiple files. In the section onprograms with multiple files, you learned that in order to use a function declared in another file, youhave to use a forward declaration, or a header file.

Similarly, in order to use a global variable that has been declared in another file, you have to use aforward declaration or a header file, along with the extern keyword. Extern tells the compiler thatyou are not declaring a new variable, but instead referring to a variable declared elsewhere.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

45 of 59 8/6/2013 4:17 PM

Page 52: Matlab Automotive QAs

Here is an example of using a forward declaration style extern:

global.cpp:

12

// declaration of g_nValue 

int g_nValue = 5;

main.cpp:

12345678

// extern tells the compiler this variable is declared elsewhere 

extern int g_nValue;

 

int main()

{

    g_nValue = 7;

    return 0;

}

Here is an example of using a header file extern:

global.cpp:

12

// declaration of g_nValue 

int g_nValue = 5;

global.h:

1234567

#ifndef GLOBAL_H // header guards

#define GLOBAL_H

 

// extern tells the compiler this variable is declared elsewhere 

extern int g_nValue;

 

#endif

main.cpp:

123456

#include "global.h" 

int main()

{

    g_nValue = 7;

    return 0;

}

Generally speaking, if a global variable is going to be used in more than 2 files, it’s better to use theheader file approach. Some programmers place all of a programs global variables in a file calledglobals.cpp, and create a header file named globals.h to be included by other .cpp files that need touse them.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

46 of 59 8/6/2013 4:17 PM

Page 53: Matlab Automotive QAs

Local variables with the same name as a global variable hide the global variable inside that block.However, the global scope operator (::) can be used to tell the compiler you mean the global version:

123456789

int nValue = 5;

 

int main()

{

    int nValue = 7; // hides the global nValue variable

    nValue++; // increments local nValue, not global nValue

    ::nValue‐‐; // decrements global nValue, not local nValue 

    return 0;

} // local nValue is destroyed

However, having local variables with the same name as global variables is usually a recipe fortrouble, and should be avoided whenever possible. Using Hungarian Notation, it is common todeclare global variables with a “g_” prefix. This is an easy way to differentiate global variable fromlocal variables, and avoid variables being hidden due to naming collisions.

New programmers are often tempted to use lots of global variables, because they are easy to workwith, especially when many functions are involved. However, this is a very bad idea. In fact, globalvariables should generally be avoided completely!

Why global variables are evil

Global variables should be avoided for several reasons, but the primary reason is because theyincrease your program’s complexity immensely. For example, say you were examining a programand you wanted to know what a variable named g_nValue was used for. Because g_nValue is aglobal, and globals can be used anywhere in the entire program, you’d have to examine every singleline of every single file! In a computer program with hundreds of files and millions of lines of code,you can imagine how long this would take!

Second, global variables are dangerous because their values can be changed by any function that iscalled, and there is no easy way for the programmer to know that this will happen. Consider thefollowing program:

123456789101112

// declare global variable

int g_nMode = 1;

 

void doSomething()

{

    g_nMode = 2;

}

 

int main()

{

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

47 of 59 8/6/2013 4:17 PM

Page 54: Matlab Automotive QAs

131415161718192021222324

    g_nMode = 1;

 

    doSomething();

 

    // Programmer expects g_nMode to be 1

    // But doSomething changed it to 2!

 

    if (g_nMode == 1)

        cout << "No threat detected." << endl;

    else

        cout << "Launching nuclear missiles..." << endl; 

 

    return 0;

}

Note that the programmer set g_nMode to 1, and then called doSomething(). Unless the programmerhad explicit knowledge that doSomething() was going to change the value of g_nMode, he or she wasprobably not expecting doSomething() to change the value! Consequently, the rest of main() doesn’twork like the programmer expects (and the world is obliterated).

Global variables make every function call potentially dangerous, and the programmer has no easyway of knowing which ones are dangerous and which ones aren’t! Local variables are much saferbecause other functions can not affect them directly. Consequently, global variables should not beused unless there is a very good reason!

41. What is the use of Complex Device Drivers in AUTOSAR?

Since the AUTOSAR layered software architecture restricts direct access to hardware from upperlayers, an additional concept is provided in order to bypass that restriction for resource critical and/orNon‐AUTOSAR compliant software components. The Complex Device Driver provides anAUTOSAR Interface to the application layer and has direct access to values on the physical layer. Thisis usually used for the implementation of complex sensor or actuator drivers that need direct controlover the underlying hardware.

 42. How to set, clear, toggle and checking a single bit in C?

Use the bitwise OR operator (|) to set a bit.

 number |= 1 << x; 

That will set bit x.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

48 of 59 8/6/2013 4:17 PM

Page 55: Matlab Automotive QAs

Clearing a bit

Use the bitwise AND operator (&) to clear a bit.

 number &= ~(1 << x); 

That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

 number ^= 1 << x; 

That will toggle bit x.

Checking a bit

You didn’t ask for this but I might as well add it.

To check a bit, AND it with the bit you want to check:

 bit = number & (1 << x); 

That will put the value of bit x into the variable bit.

42. What is Watchdog timer?

A watchdog timer (or computer operating properly (COP) timer) is a computer hardware or softwaretimer that triggers a system reset or other corrective action if the main program, due to some faultcondition, such as a hang, neglects to regularly service the watchdog (writing a “service pulse” to it,also referred to as “kicking the dog”, “petting the dog”, “feeding the watchdog” or “waking thewatchdog”). The intention is to bring the system back from the unresponsive state into normaloperation. Watchdog timers can be more complex, attempting to save debug information onto apersistent medium; i.e. information useful for debugging the problem that caused the fault. In thiscase a second, simpler, watchdog timer ensures that if the first watchdog timer does not reportcompletion of its information saving task within a certain amount of time, the system will reset withor without the information saved. The most common use of watchdog timers is in embedded

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

49 of 59 8/6/2013 4:17 PM

Page 56: Matlab Automotive QAs

systems, where this specialized timer is often a built‐in unit of a microcontroller.

 (http://automotivetechis.files.wordpress.com/2012/06/untitled4.jpg)

 43.What is the difference between 8 bit 16 bit and 32 bit processor?

Different families of micros vary in their capabilities. The number of bits just refers to the width of thedata pipe, which limits the precision of math, although many micros will either emulate higher ordermath or have special HW that can perform higher precision math functions.

The historic difference has been price: 8‐bit was cheapest, 32‐bit was expensive. This is still true ingenerally, but the price of 16‐bit parts have come down significantly.

Most 8‐bit processors are old and run on old architectures, so they tend to be slower. They are alsomade more cheaply, since that is where the competition is at the 8‐bit point, and this makes themtend towards slowness. They also tend to have a low limit on supported RAM/other storage, but theactual amount depends on the family.

16‐bit processors tend to focus on price as well, but there is a large range of parts available, some ofwhich have fairly high performance and large amounts of on‐chip peripherals. These parts usuallyperform faster than 8‐bit parts on math where the precision is greater than 8 bits, and tend to havemore addressable memory.

32‐bit chips compete primarily on performance for an application. There is a considerable range of32‐bit parts available, each targeted at some specific application. They tend to come loaded withperipherals and compete on feature completeness. They have a large amount of addressable memoryand the performance tends to be better than 16‐bit parts.

44. What is a Function Pointer ?

A function pointer is a variable that stores the address of a function that can later be called throughthat function pointer. This is useful because functions encapsulate behavior. For instance, every timeyou need a particular behavior such as drawing a line, instead of writing out a bunch of code, all youneed to do is call the function. But sometimes you would like to choose different behaviors atdifferent times in essentially the same piece of code.

Example: int (*fp) (int, int);  ‐> Function pointer returning an integer

45. Size of Datatypes

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

50 of 59 8/6/2013 4:17 PM

Page 57: Matlab Automotive QAs

Name Description Size* Range*

char Character or small integer. 1byte signed: ‐128 to 127unsigned: 0 to 255

short

int (short)

Short Integer. 2bytes signed: ‐32768 to 32767unsigned: 0 to 65535

int Integer. 4bytes signed: ‐2147483648 to2147483647unsigned: 0 to 4294967295

long

int (long)

Long integer. 4bytes signed: ‐2147483648 to2147483647unsigned: 0 to 4294967295

bool Boolean value. It can take one of twovalues: true or false.

1byte true or false

float Floating point number. 4bytes +/‐ 3.4e +/‐ 38 (~7 digits)

double Double precision floating point number. 8bytes +/‐ 1.7e +/‐ 308 (~15 digits)

long double Long double precision floating pointnumber.

8bytes +/‐ 1.7e +/‐ 308 (~15 digits)

46. What is the difference between typedef & Macros?

Typedef  is used to create a new name to an already existing data type. Redefine the name createsconflict with the previous declaration.

eg:typedef unsigned int UINT32

Macros [#define] is a direct substitution of the text before compling the whole code. In the givenexample, its just a textual substitution. where there is a posibility of redefining the macro

eg:#define chPointer  char *#undef chPointer#define chPointer int *

Typedef are used for declarations when compare with macro

typedefs can correctly encode pointer types.where as #DEFINES are just replacements done by thepreprocessor.

For example,

typedef char *String_t;1.

#define String_d char *2.

String_t s1, s2; String_d s3, s4;3.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

51 of 59 8/6/2013 4:17 PM

Page 58: Matlab Automotive QAs

s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not theintention.

47. What is the difference between a macro and a function?

Macros are essentially shorthand representations of arbitrary sections of the source code, whichmakes the source code, while its (the macro template’s) expansion replaces each of its presence priorto compilation. Whatever is there to do with Macros, it is done by the preprocessor, so that the sourcecode is ready for compilation. Function is a calling routine, whence a large program is divided intoseparate portions, each portion doing a separate job, and proper calling of these portions in differentplaces combines the works done by them into the required complete output. Thus functions havenothing to do with the preprocessing period, they are just compiled. To some extent function andmacro is similar, for a macro can occasionally be invoked to perform a task that is generally entrustedto a function. But the similarity ends there.

The differences are:

Macro consumes less time. When a function is called, arguments have to be passed to it, those

arguments are accepted by corresponding dummy variables in the function, they are processed,and finally the function returns a value that is assigned to a variable (except for a void function). Ifa function is invoked a number of times, the times add up, and compilation is delayed. On theother hand, the macro expansion had already taken place and replaced each occurrence of themacro in the source code before the source code starts compiling, so it requires no additional timeto execute.

1.

Function consumes less memory. While a function replete with macros may look succinct on

surface, prior to compilation, all the macro‐presences are replaced by their corresponding macroexpansions, which consumes considerable memory. On the other hand, even if a function isinvoked 100 times, it still occupies the same space. Hence function is more amenable to lessmemory requirements

2.

48. What is inline function?

Inline function is the optimization technique used by the compilers. One can simply prepend inlinekeyword to function prototype to make a function inline. Inline function instruct compiler to insertcomplete body of the function wherever that function got used in code.

Advantages :‐ 1) It does not require function calling overhead.2) It also save overhead of variables push/pop on the stack, while function calling.3) It also save overhead of return call from a function.4) It increases locality of reference by utilizing instruction cache.5) After in‐lining compiler can also apply intraprocedural optmization if specified. This is the mostimportant one, in this way compiler can now focus on dead code elimination, can give more stress onbranch prediction, induction variable elimination etc..

Disadvantages :‐1) May increase function size so that it may not fit on the cache, causing lots of cahce miss.2) After in‐lining function if variables number which are going to use register increases than they maycreate overhead on register variable resource utilization.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

52 of 59 8/6/2013 4:17 PM

Page 59: Matlab Automotive QAs

3) It may cause compilation overhead as if some body changes code inside inline function than allcalling location will also be compiled.4) If used in header file, it will make your header file size large and may also make it unreadable.5) If somebody used too many inline function resultant in a larger code size than it may causethrashing in memory. More and more number of page fault bringing down your programperformance.6) Its not useful for embeded system where large binary size is not preferred at all due to memorysize constraints

49. What is the difference between a macro and a inline function?

Macros :1. input argument datatype checking can’t be done.2. compiler has no idea about macros3. Code is not readable4. macros are always expanded or replaced during preprocessing, hence code size is more.5. macro can’t return.

Inline function :1. input argument datatype can be done.2. compiler knows about inline functions.3. code is readable4. inline functions are may not be expanded always5. can return.

50. Preprocessor Statements #ifdef, #else, #endif

These provide a rapid way to “clip” out and insert code.

Consider;

     #define FIRST

     main()

     {

        int a, b, c;

#ifdef FIRST

       a=2; b=6; c=4;

#else

       printf("Enter a:");

       scanf("%d", &a);

       printf("Enter a:");

       scanf("%d", &a);

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

53 of 59 8/6/2013 4:17 PM

Page 60: Matlab Automotive QAs

       printf("Enter a:");

       scanf("%d", &a);

#endif

       additonal code

Note that if FIRST is defined (which it is in the above) the values of a, b and c are hardcoded to valuesof 2, 6 and 4. This can save a lot of time when developing software as it avoids tediously typingeverything in each and everytime you run your routine. When FIRST is defined, all that is passed tothe compiler is the code between the #ifdef and the #else. The code between the #else and the #endif isnot seen by the compiler. It is as if it were all a comment.

Once you have your routine working, and desire to insert the printf and scanfs, all that is required isto go back and delete the the #define FIRST. Now, the compiler does not see the;

     a=2; b=6; c=4;

How to calculate CRC Sequence in a CAN Frame?

The receivers calculate the CRC in the same way as the transmitter as follows:

The message is regarded as polynom and is divided by the generator polynom:

x + x14 + x10 + x8 + x7 + x4 + x3 + 1 .

1.

The division rest of this modulo2 division is the CRC sequence which is transmitted together with

the message.

2.

The receiver divides the message inclusive the CRC sequence by the generator polynom.3.

A CRC error has to be detected, if the calculated result is not the same as that received in the CRCsequence. In this case the receiver discards the message and transmits an Error Frame to requestretransmission.

15

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

54 of 59 8/6/2013 4:17 PM

Page 61: Matlab Automotive QAs

51. Difference between static and dynamic RAM?

Static RAM (SRAM) – High cost & Fast

1. 4 times more expensive2. Very low access time3. Can store ¼ as much4. Information stored on RS flip‐flops5. No need for refreshing

Dynamic RAM (DRAM) – Low cost & slow

1. Low cost2. Consumes less power3. Can store 4 times as much4. Information stored on FET transistors5. Needs to be refreshed

CANoe Tool Questions:

What is difference the between IG and G block in CANalyzer/CANoe tool?

Answer:  There are two limitations to the Generator block that limit its effectiveness in complex tasks.The block is misleading for some people because it requires multiple windows for setting up thetransmit message list. The second problem is the block settings have to be set before the CANalyzermeasurement starts. No changes can be made if the measurement is running.

Fortunately, CANalyzer has another transmission block that eliminates both practical limitations: theInteractive Generator block (IG). The IG block combines the configuration windows of the Generatorblock into one window; therefore, everything can be setup in one spot. In addition, changes can bemade with the IG.

Without CAPL,can we simulate the other ECU’s CAN Messages except Test ECU in the CANSimulation Network in CANoe tool without using IG or G blocks.

How to change the baud rate in CANoe without changing the code?

The bit rate may be changed by either changing the oscillator frequency, which is usually

restricted by the processor requirements, or by specifying the length of the bit segments in “timequantum” and the prescaler value.

In Canoe tool, we can change the bus timing register 0 & 1 values for correcting the baud rate.

In Autosar, we can use post build configuration for CAN baudrate values.

What is environment variable?

Environment variables are data objects global to the CANoe environment and are used to link thefunctions of a CANoe panel to CAPL programs.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

55 of 59 8/6/2013 4:17 PM

Page 62: Matlab Automotive QAs

What is HIL and SIL testing?

Answer: Hardware‐in‐the‐loop (HIL) simulation is a technique that is used in the development andtest of complex real‐time embedded systems. HIL simulation provides an effective platform byadding the complexity of the plant under control to the test platform. The complexity of the plantunder control is included in test and development by adding a mathematical representation of allrelated dynamic systems. These mathematical representations are referred to as the “plantsimulation”. The embedded system to be tested interacts with this plant simulation.

Hardware‐In‐the‐Loop System is an effective platform for developing and testing complex real‐timeembedded systems. HIL system provides the complexity of the plant under control usingmathematical representation, called “plant simulation”, of all related dynamic systems. It alsoincludes electrical emulation of sensors and actuators which act as the interface between the plantsimulation and the embedded system under test.

Advantages of HIL System

Provides Cost Savings by Shortened Development timeComplete, consistent test coverage.Supports automated testingEnables testing the hardware without building a “plant prototype”Simulator performs test outside the normal range of operationSupports reproducible test runs that can assist in uncovering and tracking down hard to findproblems.Enables testing with less risk of destroying the system

SIL: SIL refers to the kind of testing done to validate the behavior of the C‐code used in thecontroller.  That code can be auto‐generated from the model used in algorithm development. Emmeskay has a deep understanding of SIL testing and auto‐code generation from the many SILprojects we have performed for our customers.

Testing and Validation

Plant model developed in vehicle simulation environment is imported to Simulink as a library.Controller is tested in loop with the plant for different routes and speed profiles.Controller is tested for different fault modes of the system using GUI VisualConnex

RTOS Question:

What is RTOS?

Real‐Time Operating System is a multitasking operating system intended for real‐time applications. Itis used on every device/system needing real time operations that means operations based not only oncorrectness but also upon the time (clock cycles) in which they are performed.

In general, an operating system (OS) is responsible for managing the hardware resources of acomputer and hosting applications that run on the computer. An RTOS performs these tasks, but isalso specially designed to run applications with very precise timing and a high degree of reliability.This can be especially important in measurement and automation systems where downtime is costlyor a program delay could cause a safety hazard. To be considered “real‐time”, an operating system

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

56 of 59 8/6/2013 4:17 PM

Page 63: Matlab Automotive QAs

must have a known maximum time for each of the critical operations that it performs (or at least beable to guarantee that maximum most of the time). Some of these operations include OS calls andinterrupt handling. Operating systems that can absolutely guarantee a maximum time for theseoperations are commonly referred to as “hard real‐time”, while operating systems that can onlyguarantee a maximum most of the time are referred to as “soft real‐time”.

Example: Imagine that you are designing an airbag system for a new model of car. In this case, asmall error in timing (causing the airbag to deploy too early or too late) could be catastrophic andcause injury. Therefore, a hard real‐time system is needed; you need assurance as the system designerthat no single operation will exceed certain timing constraints. On the other hand, if you were todesign a mobile phone that received streaming video, it may be ok to lose a small amount of dataoccasionally even though on average it is important to keep up with the video stream. For thisapplication, a soft real‐time operating system may suffice. An RTOS can guarantee that a programwill run with very consistent timing. Real‐time operating systems do this by providing programmerswith a high degree of control over how tasks are prioritized, and typically also allow checking tomake sure that important deadlines are met.

 How Real‐Time OSs Differ from General‐Purpose OSs?

Operating systems such as Microsoft Windows and Mac OS can provide an excellent platform fordeveloping and running your non‐critical measurement and control applications. However, theseoperating systems are designed for different use cases than real‐time operating systems, and are notthe ideal platform for running applications that require precise timing or extended up‐time. Thissection will identify some of the major under‐the‐hood differences between both types of operatingsystems, and explain what you can expect when programming a real‐time application.

Interrupt latency is measured as the amount of time between when a device generates an interruptand when that device is serviced. While general‐purpose operating systems may take a variableamount of time to respond to a given interrupt, real‐time operating systems must guarantee that allinterrupts will be serviced within a certain maximum amount of time. In other words, the interruptlatency of real‐time operating systems must be bounded

Unanswered Interview Questions   If you know comment as reply)

What is the use of Passive error node?

Error Passive receivers can no longer interrupt the data transfer as a recessive Error Flag does notinfluence the bus levels. An Error Passive transmitter can still interrupt its own message by sending apassive Error Flag. Attention, if one Receiver is in error passive mode no data consistency isguaranteed any more.

How to find the bug in code using debugger if pointer is  pointing to a  illegal value?

If two CAN messages with same ID sending at a same time, different data which can node will

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

57 of 59 8/6/2013 4:17 PM

Page 64: Matlab Automotive QAs

gain arbitration? How to test it?

Is it possible to declare struct and union one inside other? Explain with example

Spi and I2C difference.?1.

What is UDS advantages?2.

What is cross compiler3.

Unit/integration/all testings.4.

Regression testing.5.

Test case types.6.

Malloc calloc7.

Function pointers Advantage where it is used?8.

How many can database files are required for CAN Network simulation in CANoe tool.

what is the difference between CANalyzer,CANoe and CANape tools?

Mention the few uses of the CANoe tool?

what is a panel is CANoe Tool and its Use?

Why CAPL scripting is used in CANoe tool?

Is it possible to simulate other ECU’s Except Test ECU without CAPL Scripting in CANoe tool?

what is purpose of CCP protocol which is also used in CANape tool?

Embedded Development Documents:

 Introduction_to_prog_embedded_systems (http://automotivetechis.files.wordpress.com/2012/06

/lec‐into_to_prog_embedded_systems.pdf)  youtube http://www.youtube.com/watch?v=sw3ADKPo1Uo&feature=player_detailpage%5D

(http://www.youtube.com/watch?v=sw3ADKPo1Uo&feature=player_detailpage%5D)

Prateek DewanganJULY 1, 2013 @ 3:38 PMI must Say thanks for this articel

REPLYVijaisankarJULY 24, 2013 @ 6:54 AMsuperb generally covered….and the performance of a candiadate depends on how he presents andhis past experience.Thanks a lot.

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

58 of 59 8/6/2013 4:17 PM

Page 65: Matlab Automotive QAs

REPLYpavanAUGUST 2, 2013 @ 8:54 AMtruly goodThanks.

REPLYSonaliAUGUST 2, 2013 @ 11:51 AMThank you very much for this artical…it is really helpful….

REPLY

Blog at WordPress.com. | The iTheme2 Theme.

Follow

Powered by WordPress.com

Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/

59 of 59 8/6/2013 4:17 PM

Page 66: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 1 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

A BRIEF LIST OF MATLAB COMMANDS Some Basic Commands (Note command syntax is case-sensitive!) matlab loads the program matlab into your workspace. quit quits matlab, returning you to the operating system. exit same as quit. who lists all of the variables in your matlab workspace. whos list the variables and describes their matrix size. clear deletes all matrices from active workspace. clear x deletes the matrix x from active workspace. ... the ellipsis defining a line continuation is three successive periods. save saves all the matrices defined in the current session into the file, matlab.mat. load loads contents of matlab.mat into current workspace. save filename saves the contents of workspace into filename.mat save filename x y z saves the matrices x, y and z into the file titled filename.mat. load filename loads the contents of filename into current workspace; the file can be a binary (.mat) file or an ASCII file. ! the ! preceding any unix command causes the unix command to be executed from matlab. Commands Useful in Plotting. plot(x,y) creates an Cartesian plot of the vectors x & y. plot(y) creates a plot of y vs. the numerical values of the elements in the y-vector. semilogx(x,y) plots log(x) vs y. semilogy(x,y) plots x vs log(y) loglog(x,y) plots log(x) vs log(y). grid creates a grid on the graphics plot. title('text') places a title at top of graphics plot. xlabel('text') writes 'text' beneath the x-axis of a plot. ylabel('text') writes 'text' beside the y-axis of a plot. text(x,y,'text') writes 'text' at the location (x,y) . text(x,y,'text','sc') writes 'text' at point x,y assuming lower left corner is (0,0) and upper right corner is (1,1). gtext('text') writes text according to placement of mouse hold on maintains the current plot in the graphics window while executing subsequent plotting commands. hold off turns OFF the 'hold on' option. polar(theta,r) creates a polar plot of the vectors r & theta where theta is in radians. bar(x) creates a bar graph of the vector x. (Note also the command stairs(y).) bar(x,y) creates a bar-graph of the elements of the vector y, locating the bars according to the vector elements of 'x'. (Note also the command stairs(x,y).) hist(x) creates a histogram. This differs from the bargraph

Page 67: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 2 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

in that frequency is plotted on the vertical axis. mesh(z) creates a surface in xyz space where z is a matrix of the values of the function z(x,y). z can be interpreted to be the height of the surface above some xy reference plane. surf(z) similar to mesh(z), only surface elements depict the surface rather than a mesh grid. contour(z) draws a contour map in xy space of the function or surface z. meshc(z) draws the surface z with a contour plot beneath it. meshgrid [X,Y]=meshgrid(x,y) transforms the domain specified by vectors x and y into arrays X and Y that can be used in evaluating functions for 3D mesh/surf plots. print sends the contents of graphics window to printer. print filename -dps writes the contents of current graphics to 'filename' in postscript format. Equation Fitting polyfit(x,y,n) returns the coefficients of the n-degree polynomial for the vectors x and y. n must be at least 1 larger than the length of the vectors x and y. If n+1 = length(x) the result is an interpolating polynomial. If n+1 > length(x) the result is a least-squares polynomial fit. The coefficients are stored in order with that of the highest order term first and the lowest order last. polyval(c,x) calculates the values of the polynomial whose coefficients are stored in c, calculating for every value of the vector x. Data Analysis Commands max(x) returns the maximum value of the elements in a vector or if x is a matrix, returns a row vector whose elements are the maximum values from each respective column of the matrix. min (x) returns the minimum of x (see max(x) for details). mean(x) returns the mean value of the elements of a vector or if x is a matrix, returns a row vector whose elements are the mean value of the elements from each column of the matrix. median(x) same as mean(x), only returns the median value. sum(x) returns the sum of the elements of a vector or if x is a matrix, returns the sum of the elements from each respective column of the matrix. prod(x) same as sum(x), only returns the product of elements. std(x) returns the standard deviation of the elements of a vector or if x is a matrix, a row vector whose elements are the standard deviations of each column of the matrix. sort(x) sorts the values in the vector x or the columns of a matrix and places them in ascending order. Note that this command will destroy any association that may exist between the elements in a row of matrix x. hist(x) plots a histogram of the elements of vector, x. Ten

Page 68: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 3 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

bins are scaled based on the max and min values. hist(x,n) plots a histogram with 'n' bins scaled between the max and min values of the elements. hist((x(:,2)) plots a histogram of the elements of the 2nd column from the matrix x. fliplr(x) reverses the order of a vector. If x is a matrix, this reverse the order of the columns in the matrix. flipud(x) reverses the order of a matrix in the sense of exchanging or reversing the order of the matrix rows. This will not reverse a row vector! reshape(A,m,n) reshapes the matrix A into an mxn matrix from element (1,1) working column-wise. SPECIAL MATRICES zeros(n) creates an nxn matrix whose elements are zero. zeros(m,n) creates a m-row, n-column matrix of zeros. ones(n) creates a n x n square matrix whose elements are 1's ones(m,n)' creates a mxn matrix whose elements are 1's. ones(A) creates an m x n matrix of 1's, where m and n are based on the size of an existing matrix, A. zeros(A) creates an mxn matrix of 0's, where m and n are based on the size of the existing matrix, A. eye(n) creates the nxn identity matrix with 1's on the diagonal. Miscellaneous Commands length(x) returns the number elements in a vector. size(x) returns the size m(rows) and n(columns) of matrix x. rand returns a random number between 0 and 1. randn returns a random number selected from a normal distribution with a mean of 0 and variance of 1. rand(A) returns a matrix of size A of random numbers. ALGEBRAIC OPERATIONS IN MATLAB Scalar Calculations. + addition - subtraction * multiplication / right division (a/b means a ÷ b) \ left division (a\b means b ÷ a) ^ exponentiation The precedence or order of the calculations included in a singleline of code follows the below order: Precedence Operation

Page 69: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 4 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

1 parentheses 2 exponentiation, left to right 3 multiplication and division, left right 4 addition and subtraction, left right MATRIX ALGEBRA In matrix multiplication, the elements of the product, C, oftwo matrices A*B is calculated from Cij = ‘ (Aik * Bkj) {summation over the double index k} To form this sum, the number of columns of the first or left matrix(A) must be equal to the number of rows in the second or rightmatrix (B). The resulting product, matrix C, has an order for whichthe number of rows equals the number of rows of the first (left)matrix (A) and the product (C) has a number of columns equal to thenumber of columns in the second (right) matrix (B). It is clearthat A*B IS NOT NECESSARILY EQUAL TO B*A! The PRODUCT OF A SCALAR AND A MATRIX is a matrix in whichevery element of the matrix has been multiplied by the scalar. ARRAY PRODUCTS Sometimes it is desired to simply multiply or divide eachelement of an matrix by the corresponding element of anothermatrix. These are called 'array operations" in 'matlab'. Array orelement-by-element operations are executed when the operator ispreceded by a '.' (period). Thus a .* b multiplies each element of a by the respective element of b a ./ b divides each element of a by the respective element of b a .\ b divides each element of b by the respective element of a a .^ b raise each element of a by the respective b element TRANSPOSE OF A MATRIX x' The transpose of a matrix is obtained by interchanging the rows and columns. The 'matlab' operator that creates the transpose is the single quotation mark, '. INNER PRODUCT OF TWO VECTORS The inner product of two row vectors G1 and G2 is G1*G2'. The inner product of two column vectors H and J is H'*J. OUTER PRODUCT OF TWO VECTORS If two row vectors exist, G1 and G2, the outer product issimply G1' * G2 {Note G1' is nx1 and G2 is 1xn}

Page 70: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 5 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

and the result is a square matrix in contrast to the scalar resultfor the inner product. DON'T CONFUSE THE OUTER PRODUCT WITH THEVECTOR PRODUCT IN MECHANICS! If the two vectors are column vectors,the outer product must be formed by the product of one vector timesthe transpose of the second! SOLUTION TO SIMULTANEOUS EQUATIONS Using the Matrix Inverse inv(a) returns the inverse of the matrix a. If ax=b is a matrix equation and a is the coefficient matrix, the solution x is x=inv(a)*b. Using Back Substitution a\b returns a column vector solution for the matrix equation ax=b where a is a coefficient matrix. b/a returns a row vector solution for the matrix equation xa=b where a is a coefficient matrix.

Some basic commands you will need: matlab loads the program matlab into your workspace quit quits matlab, returning you to the operating system exit same as quit who lists all of the variables in your matlab workspace whos list the variables and describes their matrix size NOTE - When using the workstations, clicking on UP ARROW willrecall previous commands. If you make a mistake, the DELETE key ORthe backspace key may be used to correct the error; however, one ofthese two keys may be inoperable on particular systems. 'matlab' uses variables that are defined to be matrices. Amatrix is a collection of numerical values that are organized intoa specific configuration of rows and columns. The number of rowsand columns can be any number, for example, 3 rows and 4 columnsdefine a 3 x 4 matrix which has 12 elements in total. A scalar isrepresented by a 1 x 1 matrix in matlab. A vector of n dimensionsor elements can be represented by a n x 1 matrix, in which case itis called a column vector, or a vector can be represented by a 1 xn matrix, in which case it is called a row vector of n elements.The matrix name can be any group of letters and numbers up to 19,but always beginning with a letter. Thus 'x1' can be a variablename, but '1x' is illegal. 'supercalafragilesticexpealladotious'can be a variable name; however, only the first 19 characters willbe stored! Understand that 'matlab' is "case sensitive", that is,it treats the name 'C' and 'c' as two different variables.Similarly, 'MID' and 'Mid' are treated as two different variables.Here are examples of matrices that could be defined in 'matlab'.Note that the set of numerical values or elements of the matrix arebounded by brackets ......[ ].

Page 71: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 6 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

c = 5.66 or c = [5.66] c is a scalar or a 1 x 1 matrix x = [ 3.5, 33.22, 24.5 ] x is a row vector or 1 x 3 matrix x1 = [ 2 x1 is column vector or 5 4 x 1 matrix 3 -1] A = [ 1 2 4 A is a 4 x 3 matrix 2 -2 2 0 3 5 5 4 9 ] An individual element of a matrix can be specified with thenotation A(i,j) or Ai,j for the generalized element, or by A(4,1)=5for a specific element. When 'matlab' prints a matrix on the monitor, it will be organizedaccording to the size specification of the matrix, with each rowappearing on a unique row of the monitor screen and with eachcolumn aligned vertically and right-justified. The numerical values that are assigned to the individual elementsof a matrix can be entered into the variable assignment in a numberof ways. The simplest way is by direct keyboard entry; however,large data sets may be more conveniently entered through the use ofstored files or by generating the element values using matlabexpressions. First, we will look at the use of the keyboard fordirect entry. KEYBOARD DEFINITION OR ENTRY FOR A MATRIX A matrix can be defined by a number of matlab expressions. Examplesare listed below for a 1 x 3 row vector, x, whose elements are x(1) = 2, x(2) = 4 and x(3) = -1. x = [ 2 4 -1 ] or x=[2 4 -1] or x = [ 2,4,-1 ] (A keystroke 'enter' follows each of the above matlab statements.)Notice that brackets must be used to open and close the set ofnumbers, and notice that commas or blanks may be used as delimitersbetween the fields defining the elements of the matrix. Blanks usedaround the = sign and the brackets are superfluous; however, theysometimes make the statement more readable. A 2x4 matrix, y, whose elements are y(1,1)=0, y(1,2) = y(1,3) = 2,y(1,4) = 3, y(2,1) = 5, y(2,2) = -3, y(2,3) = 6 and y(2,4) = 4 canbe defined y = [ 0 2 2 3 5 -3 6 4 ]

Page 72: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 7 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

or y = [ 0 2 2 3 ; 5 -3 6 4 ] The semicolon ";" is used to differentiate the matrix rows whenthey appear on a single line for data entry. The elements of a matrix can be defined with algebraic expressionsplaced at the appropriate location of the element. Thus a = [ sin(pi/2) sqrt(2) 3+4 6/3 exp(2) ] defines the matrix a = [ 1.0000 1.4142 7.0000 2.0000 7.3891 ] A matrix can be defined by augmenting previously defined matrices.Recalling the matrix, x, defined earlier x1 = [ x 5 8 ] creates the result x1 = [ 2 4 -1 5 8 ] The expression x(5) = 8 creates x = [ 2 4 -1 0 8 ] Notice that the value "0" is substituted for x(4) which has notbeen explicitly defined. Recalling the definition of matrix, y, above, the expressions c = [ 4 5 6 3 ] z = [ y;c ] creates z = [ 0 2 2 3 5 -3 6 4 4 5 6 3 ] Note that every time a matrix is defined and an 'enter' keystrokeis executed, matlab echoes back the result. TO CANCEL THIS ECHO,THE MATLAB COMMAND LINE CAN INCLUDE A SEMICOLON AT THE END OF THELINE BEFORE THE KEYSTROKE 'ENTER'. z = [ y ; c ] ; LINE CONTINUATION Occasionally, a line is so long that it can not be expressed inthe 80 spaces available on a line, in which case a linecontinuation is needed. In matlab, the ellipsis defining a linecontinuation is three successive periods, as in "...". Thus

Page 73: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 8 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

4 + 5 + 3 ... + 1 + 10 + 2 ... + 5 gives the result ans = 30 Notice that in this simple arithmetic operation, no matrix wasdefined. When such an operation is executed in matlab, the resultis assigned to the matrix titled "ans". A subsequent operationwithout an assignment to a specific matrix name will replace theresults in 'ans' by the result of the next operation. In the above,'ans' is a 1x1 matrix, but it need not be so in general. BEFORE YOU QUIT THIS SESSION !!!!! If this is your first lesson using matlab, execute the matlabcommands 'who' and whos' before you 'quit'. Note that each of thesecommands lists the matrices you have defined in this session on thecomputer. The command 'whos' also tells you the properties of eachmatrix, including the number of elements, the row and column size(row x column) and whether the elements are complex or real. IMPORTANT! If you execute the matlab command 'save' before youquit, all of the matrices that have been defined will be saved ina file titled matlab.mat stored in your workspace. Should youdesire to save specific matrices during any session, the command'save' followed by the name of the matrix can be executed. Moredetail on how to save and recall your matrices is discussed in Lesson 2. PRACTICE PROBLEMS Determine the size and result for the following matrices. Subsequently, carry out the operations on matlab that define thematrices, and check your results using the 'whos' statement. 1. a = [1,0,0,0,0,1] 2. b = [2;4;6;10] 3. c = [5 3 5; 6 2 -3] 4. d= [3 4 5 7 9 10 ] 5. e = [3 5 10 0; 0 0 ... 0 3; 3 9 9 8 ] 6. t = [4 24 9] q = [t 0 t] 7. x = [ 3 6 ]

Page 74: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 9 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

y = [d;x] z = [x;d] 8. r = [ c; x,5] 9. v = [ c(2,1); b ] 10. a(2,1) = -3 (NOTE: Recall matrix "a" was defined in (1) above.)

New commands in this lesson: save saves all the matrices defined in the current session into the file, matlab.mat, located in the directory from which you executed matlab. load loads contents of matlab.mat into current workspace save filename x y z save the matrices x, y and z into the file titled filename.mat. load filename loads the contents of filename into current workspace; the file can be a binary (.mat) file or an ASCII file. clear x erases the matrix 'x' from your workspace clear erases ALL matrices from your workspace NOTE - When using PROMATLAB on a workstation, files are stored inthe directory from which you invoked the 'matlab' command. Whenusing the workstation, create a matlab subdirectory titled 'matlab'or some similar name. Thereafter, store all files and conduct allmatlab sessions in that subdirectory. ASCII FILES An ASCII file is a file containing characters in ASCII format, aformat that is independent of 'matlab' or any other executableprogram. Using ASCII format, you can build a file using a screeneditor or a wordprocessing program, for example, that can be readand understood by 'matlab'. The file can be read into 'matlab'using the "load" command described above. Using a text editor or using a wordprocessor that is capable ofwriting a file in ASCII format, you simply prepare a matrix filefor which EACH ROW OF THE MATRIX IS A UNIQUE LINE IN THE FILE, withthe elements in the row separated by blanks. An example is the 3 x3 matrix 2 3 6 3 -1 0 7 0 -2 If these elements are formatted as described above and stored in afilename titled, for example, x.dat, the 3 x 3 matrix 'x' can be

Page 75: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 10 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

loaded into 'matlab' by the command load x.dat Open the Text Editor window on your workstation. Build a 3x3matrix in the editor that follows the format explained above. Store this in your matlab directory using the command save ~/matlab/x.dat The suffix, .dat, is not necessary; however, it is stronglyrecommended here to distinguish the file from other data files,such as the .mat files which will be described below. Of course ifyou define the file with the .dat or any other suffix, you must usethat suffix when downloading the file to 'matlab' with the 'load'command. Remember, the file must be stored in the directory inwhich you are executing matlab. In the above example, it isassumed that this directory is titled 'matlab'. Now go to a window in which matlab is opened. We desire toload the matrix x into matlab. We might wonder if the file x.datis actually stored in our matlab directory. To review what filesare stored therein, the unix command 'ls' can be evoked in matlabby preceding the command with an exclamation mark, ! . Type thecommand ! ls Matlab will list all of the files in your directory. You shouldfind one titled "x.dat". Now, type the command load x.dat The 3x3 matrix defined above is now down-loaded into your workingspace in matlab. To ensure that is so, check your variables bytyping 'who' or 'whos'. FILES BUILT BY MATLAB....THE .mat FILE If at any time during a matlab session you wish to store a matrixthat has been defined in the workspace, the command save filename will create a file in your directory that is titled filename.mat.The file will be in binary format, understandable only by the'matlab' program. Note that 'matlab' appends the .mat suffix andthis can be omitted by the user when describing the filename. If the matrix 'x' has been defined in the workspace, it can bestored in your directory in binary matlab format with the command save x The filename need not be the same as the matrix name. The file

Page 76: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 11 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

named, for example, 'stuff' can be a file that contains the matrix'x'. Any number of matrices can be stored under the filename. Thusthe command string save stuff x y z will store the matrices x, y and z in the file titled 'stuff'. Thefile will automatically have the suffix .mat added to thefilename. If, during a session, you type the command 'save' withno other string, all of the current matrices defined in yourworkspace will be stored in the file 'matlab.mat'. The load command when applied to .mat files follows the sameformat as discussed above for ASCII files; however, you can omitthe file suffix '.mat' when loading .mat files to your workspace. COLON OPERATOR The colon operator ' : ' is understood by 'matlab' to performspecial and useful operations. If two integer numbers are separatedby a colon, 'matlab' will generate all of the integers betweenthese two integers. a = 1:8 generates the row vector, a = [ 1 2 3 4 5 6 7 8 ]. If three numbers, integer or non-integer, are separated by twocolons, the middle number is interpreted to be a "range" and thefirst and third are interpreted to be "limits". Thus b = 0.0 : .2 : 1.0 generates the row vector b = [ 0.0 .2 .4 .6 .8 1.0 ] The colon operator can be used to create a vector from a matrix.Thus if x = [ 2 6 8 0 1 7 -2 5 -6 ] The command y = x(:,1) creates the column vector y = [ 2 0 -2 ] and yy = x(:,2) creates yy = [ 6

Page 77: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 12 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

1 5 ] The command z = x(1,:) creates the row vector z = [ 2 6 8 ] The colon operator is useful in extracting smaller matrices fromlarger matrices. If the 4 x 3 matrix c is defined by c = [ -1 0 0 1 1 0 1 -1 0 0 0 2 ]Then d1 = c(:,2:3) creates a matrix for which all elements of the rows from the 2ndand third columns are used. The result is a 4 x 2 matrix d1 = [ 0 0 1 0 -1 0 0 2 ] The command d2 = c(3:4,1:2) creates a 2 x 2 matrix in which the rows are defined by the 3rd and4th row of c and the columns are defined by the 1st and 2nd columnsof the matrix, c. d2 = [ 1 -1 0 0 ] USING THE CLEAR COMMANDS Before quitting this session of 'matlab', note the use of thecommands 'clear' and 'clc'. Note that 'clc' simply clears thescreen, but does not clear or erase any matrices that have beendefined. The command 'clear' erase or removes matrices from yourworkspace. Use this command with care. NOTE THE COMMAND 'CLEAR'WITHOUT ANY MODIFYING STRING WILL ERASE ALL MATRICES IN YOURWORKSPACE. PROBLEMS Define the 5 x 4 matrix, g. g = [ 0.6 1.5 2.3 -0.5

Page 78: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 13 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

8.2 0.5 -0.1 -2.0 5.7 8.2 9.0 1.5 0.5 0.5 2.4 0.5 1.2 -2.3 -4.5 0.5 ] Determine the content and size of the following matrices and checkyour results for content and size using 'matlab'. 1. a = g(:,2) 2. b = g(4,:) 3. c = [10:15] 4. d = [4:9;1:6] 5. e = [-5,5] 6. f= [1.0:-.2:0.0] 7. t1 = g(4:5,1:3) 8. t2 = g(1:2:5,:)

New commands in this lesson: plot(x,y) creates a Cartesian plot of the vectors x & y plot(y) creates a plot of y vs. the numerical values of the elements in the y-vector. semilogx(x,y) plots log(x) vs y semilogy(x,y) plots x vs log(y) loglog(x,y) plots log(x) vs log(y) grid creates a grid on the graphics plot title('text') places a title at top of graphics plot xlabel('text') writes 'text' beneath the x-axis of a plot ylabel('text') writes 'text' beside the y-axis of a plot text(x,y,'text') writes 'text' at the location (x,y) text(x,y,'text','sc') writes 'text' at point x,y assuming lower left corner is (0,0) and upper right corner is (1,1). polar(theta,r) creates a polar plot of the vectors r & theta where theta is in radians. bar(x) creates a bar graph of the vector x. (Note also the command stairs(x).)

Page 79: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 14 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

bar(x,y) creates a bar-graph of the elements of the vector y, locating the bars according to the vector elements of 'x'. (Note also the command stairs(x,y).) CARTESIAN OR X-Y PLOTS One of 'matlab' most powerful features is the ability tocreate graphic plots. Here we introduce the elementary ideas forsimply presenting a graphic plot of two vectors. More complicatedand powerful ideas with graphics can be found in the 'matlab'documentation. A Cartesian or orthogonal x,y plot is based on plotting thex,y data pairs from the specified vectors. Clearly, the vectors xand y must have the same number of elements. Imagine that you wishto plot the function ex for values of x from 0 to 2.x = 0:.1:2;y = exp(x);plot(x,y) NOTE: The use of selected functions such as exp() and sin() will beused in these tutorials without explanation if they take on anunambiguous meaning consistent with past experience. Here it isobserved that operating on a matrix with these functions simplycreates a matrix in which the elements are based on applying thefunction to each corresponding element of the argument. Of course the symbols x,y are arbitrary. If we wanted to plottemperature on the ordinate and time on the abscissa, and vectorsfor temperature and time were loaded in 'matlab', the command wouldbe plot(time,temperature) Notice that the command plot(x,y) opens a graphics window. If younow execute the command 'grid', the graphics window is redrawn.(Note you move the cursor to the command window before typing newcommands.) To avoid redrawing the window, you may use the linecontinuation ellipsis. Considerplot(x,y),...grid,...title('Exponential Function'),...xlabel('x'),...ylabel('exp(x)'),text(.6,.4,' y = exp(x)','sc') Note that if you make a mistake in typing a series of lines ofcode, such as the above, the use of line continuation can befrustrating. In a future lesson, we will learn how to create batchfiles (called '.m' files) for executing a series of 'matlab'commands. This approach gives you better opportunity to return tothe command string and edit errors that have been created. Having defined the vectors x and y, construct semilog and log-log plots using these or other vectors you may wish to create. Note

Page 80: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 15 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

in particular what occurs when a logarithmic scale is selected fora vector that has negative or zero elements. Here, the vector x hasa zero element (x(1)=0). The logarithm of zero or any negativenumber is undefined and the x,y data pair for which a zero ornegative number occurs is discarded and a warning message provided. Try the commands plot(x) and plot(y) to ensure you understandhow they differ from plot(x,y). Notice that 'matlab' draws a straight line between the data-pairs. If you desire to see a relatively smooth curve drawn for arapidly changing function, you must include a number of datapoints. For example, consider the trigonometric function, sin(x1)(x1 is selected as the argument here to distinguish it from thevector 'x' that was defined earlier. ) Plot sin(x1) over the limits 0 <= x1 <= pi. First define x1with 5 elements, x1 = 0 : pi/4 : piy1 = sin(x1)plot(x1,y1) Now, repeat this after defining a new vector for x1 and y1 with 21elements. (Note the use of the semicolon here to prevent theprinting and scrolling on the monitor screen of a vector or matrixwith a large number of elements!)x1 = 0 : .05*pi : pi ;y1 =sin(x1);plot(x1,y1) POLAR PLOTS Polar plots are constructed much the same way as are Cartesianx-y plots; however, the arguments are the angle 'theta' in radiansmeasured CCW from the horizontal (positive-x) axis, and the lengthof the radius vector extended from the origin along this angle.Polar plots do not allow the labeling of axes; however, notice thatthe scale for the radius vector is presented along the vertical andwhen the 'grid' command is used the angles-grid is presented in 15-degree segments. The 'title' command and the 'text' commands arefunctional with polar plots.angle = 0:.1*pi:3*pi;radius = exp(angle/20);polar(angle,radius),...title('An Example Polar Plot'),...grid Note that the angles may exceed one revolution of 2*pi. BAR GRAPHS To observe how 'matlab' creates a bargraph, return to thevectors x,y that were defined earlier. Create bar and stair graphsusing these or other vectors you may define. Of course the 'title'and 'text' commands can be used with bar and stair graphs.

Page 81: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 16 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

bar(x,y) and bar(y) stair (x,y) and stair(y) MULTIPLE PLOTS More than a single graph can be presented on one graphic plot.One common way to accomplish this is hold the graphics window openwith the 'hold' command and execute a subsequent plotting command. x1=0:.05*pi:pi;y1=sin(x1);plot(x1,y1)holdy2=cos(x1);plot(x1,y2) The "hold" command will remain active until you turn it off withthe command 'hold off'. You can create multiple graphs by using multiple arguments. In addition to the vectors x,y created earlier, create the vectorsa,b and plot both vector sets simultaneously as follows.a = 1 : .1 : 3;b = 10*exp(-a);plot(x,y,a,b) Multiple plots can be accomplished also by using matricesrather than simple vectors in the argument. If the arguments ofthe 'plot' command are matrices, the COLUMNS of y are plotted onthe ordinate against the COLUMNS of x on the abscissa. Note that xand y must be of the same order! If y is a matrix and x is avector, the rows or columns of y are plotted against the elementsof x. In this instance, the number of rows OR columns in the matrixmust correspond to the number of elements in 'x'. The matrix 'x'can be a row or a column vector! Recall the row vectors 'x' and 'y' defined earlier. Augmentthe row vector 'y' to create the 2-row matrix, yy.yy=[y;exp(1.2*x)];plot(x,yy) PLOTTING DATA POINTS & OTHER FANCY STUFF Matlab connects a straight line between the data pairsdescribed by the vectors used in the 'print' command. You may wishto present data points and omit any connecting lines between thesepoints. Data points can be described by a variety of characters ( . , + , * , o and x .) The following command plots the x,y dataas a "curve" of connected straight lines and in addition places an'o' character at each of the x1,y1 data pairs. plot(x,y,x1,y1,'o')

Page 82: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 17 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

Lines can be colored and they can be broken to makedistinctions among more than one line. Colored lines are effectiveon the color monitor and color printers or plotters. Colors areuseless on the common printers used on this network. Colors aredenoted in 'matlab' by the symbols r(red), g(green), b(blue),w(white) and i(invisible). The following command plots the x,ydata in red solid line and the r,s data in broken green line. plot(x,y,'r',r,s,'--g') PRINTING GRAPHIC PLOTS Executing the 'print' command will send the contents of thecurrent graphics widow to the local printer. You may wish to save in a graphics file, a plot you havecreated. To do so, simply append to the 'print' command the nameof the file. The command print filename will store the contents of the graphics window in the file titled'filename.ps' in a format called postscript. You need not includethe .ps suffix, as matlab will do this. When you list the filesin your matlab directory, it is convenient to identify any graphicsfiles by simply looking for the files with the .ps suffix. Ifyou desire to print one of these postscript files, you canconveniently "drag and drop" the file from the file-manager windowinto the printer icon.

Commands introduced in this lesson: max(x) returns the maximum value of the elements in a vector or if x is a matrix, returns a row vector whose elements are the maximum values from each respective column of the matrix. min (x) returns the minimum of x (see max(x) for details). mean(x) returns the mean value of the elements of a vector or if x is a matrix, returns a row vector whose elements are the mean value of the elements from each column of the matrix. median(x) same as mean(x), only returns the median value. sum(x) returns the sum of the elements of a vector or if x is a matrix, returns the sum of the elements from each respective column of the matrix. prod(x) same as sum(x), only returns the product of elements. std(x) returns the standard deviation of the elements of a vector or if x is a matrix, a row vector whose elements are the standard deviations of each column of the matrix.

Page 83: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 18 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

sort(x) sorts the values in the vector x or the columns of a matrix and places them in ascending order. Note that this command will destroy any association that may exist between the elements in a row of matrix x. hist(x) plots a histogram of the elements of vector, x. Ten bins are scaled based on the max and min values. hist(x,n) plots a histogram with 'n' bins scaled between the max and min values of the elements. hist((x(:,2)) plots a histogram of the elements of the 2nd column from the matrix x. The 'matlab' commands introduced in this lesson performsimple statistical calculations that are mostly self-explanatory.A simple series of examples are illustrated below. Note that'matlab' treats each COLUMN OF A MATRIX as a unique set of "data",however, vectors can be row or column format. Begin the exerciseby creating a 12x3 matrix that represents a time history of twostochastic temperature measurements. Load these data into a matrix called 'timtemp.dat' using aneditor to build an ASCII file. Time(sec) Temp-T1(K) Temp-T2(K) 0.0 306 125 1.0 305 121 2.0 312 123 3.0 309 122 4.0 308 124 5.0 299 129 6.0 311 122 7.0 303 122 8.0 306 123 9.0 303 127 10.0 306 124 11.0 304 123 Execute the commands at the beginning of the lesson above andobserve the results. Note that when the argument is 'timtemp', amatrix, the result is a 1x3 vector. For example, the command M = max(timtemp)gives M = 11 312 129 If the argument is a single column from the matrix, thecommand identifies the particular column desired. The command M2 = max(timtemp(:,2))gives M2 = 312 If the variance of a set of data in a column of the matrix isdesired, the standard deviation is squared. The command

Page 84: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 19 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

T1_var = (std(timtemp(:,2)))^2gives T1_var = 13.2727 If the standard deviation of the matrix of data is found using STDDEV = std(timtemp)gives STDDEV = 3.6056 3.6432 2.3012 Note that the command VAR = STDDEV^2 is not acceptable; however, the command VAR = STDDEV.^2 is acceptable, creating the results, VAR = 13.0000 13.2727 5.2955

USING m-FILES - SCRATCH and FUNCTION FILES Sometimes it is convenient to write a number of lines of'matlab' code before executing the commands. We have seen how thiscan be accomplished using the line continuation ellipsis; however,it was noted in this approach that any mistake in the code requiredthe entire string to be entered again. Using an m-file we canwrite a number of lines of 'matlab' code and store it in a filewhose name we select with the suffix '.m' added. Subsequently thecommand string or file content can be executed by invoking the nameof the file while in 'matlab'. This application is called aSCRATCH FILE. On occasion it is convenient to express a function in 'matlab'rather than calculating or defining a particular matrix. The many'matlab' stored functions such as sin(x) and log(x) are examples offunctions. We can write functions of our definition to evaluateparameters of our particular interest. This application of m-filesis called FUNCTION FILES. SCRATCH FILES A scratch file must be prepared in a text editor in ASCIIformat and stored in the directory from which you invoked thecommand to download 'matlab'. The name can be any legitimate filename with the '.m' suffix. As an example, suppose we wish to prepare a x-y plot of thefunction y = e-x/10 sin(x) 0 x ø 10 . To accomplish this using a scratch ".m-file", we will call the file'explot.m'. Open the file in a text editor and type the codebelow. (Note the use of the '%' in line 1 below to create a

Page 85: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 20 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

comment. Any text or commands typed on a line after the'%' will betreated as a comment and ignored in the executable code.)% A scratch m-file to plot exp(-x/10)sin(x)x = [ 0:.2:10 ];y = exp(-x/10) .* sin(x);plot(x,y),...title('EXPONENTIAL DAMPED SINE FUNCTION'),...xlabel('x'),...ylabel('y'),...text(.6,.7,'y = exp(-x/10)*sin(x)','sc') Store this file under the name 'explot.m in your 'matlab'directory. Now when you are in 'matlab', any time you type thecommand 'explot' the x-y plot of the damped exponential sinefunction will appear. FUNCTION FILES Suppose that you wish to have in your 'matlab' workspace afunction that calculates the sine of the angle when the argument isin degrees. The matlab function sin(x) requires that x be inradians. A function can be written that use the 'matlab' sin(x)function, where x is in radians, to accomplish the objective ofcalculating the sine of an argument expressed in degrees. Again,as in the case of the scratch file, we must prepare the file inASCII format using a text editor, and we must add the suffix '.m'to the file. HERE THE NAME OF THE FILE MUST BE THE NAME OF THEFUNCTION. The following code will accomplish our objective. Note that thefirst line must always begin with the word "function" followed bythe name of the function expressed as " y = function-name". Herethe function name is "sind(x)". This is the name by which we willcall for the function once it is stored. function y = sind(x)% This function calculates the sine when the argument is degrees% Note that array multiplication and division allows this to% operate on scalars, vectors and matrices.y = sin( x .* pi ./ 180 ) Again, note the rule in writing the function is to express in thefirst line of the file the word 'function', followed by y = function call,here 'sind' with the function argument in parentheses, 'x' is thefunction call. Thus, function y=sind(x) Now every time we type sind(x) in 'matlab', it will return thevalue of the sine function calculated under the assumption that xis in degrees. Of course any matrix or expression involving amatrix can be written in the argument.

ALGEBRAIC OPERATIONS IN MATLAB

Page 86: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 21 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

Scalar Calculations. The common arithmetic operators used inspreadsheets and programming languages such as BASIC are used in'matlab'. In addition a distinction is made between right and leftdivision. The arithmetic operators are + addition - subtraction * multiplication / right division (a/b means a ÷ b) \ left division (a\b means b ÷ a) ^ exponentiation When a single line of code includes more than one of theseoperators the precedence or order of the calculations follows thebelow order: Precedence Operation 1 parentheses 2 exponentiation, left to right 3 multiplication and division, left right 4 addition and subtraction, left right These rules are applied to scalar quantities (i.e., 1x1 matrices)in the ordinary manner. (Below we will discover that nonscalarmatrices require additional rules for the application of theseoperators!!) For example, 3*4 executed in 'matlab' gives ans=12 4/5 executed in 'matlab' gives ans=.8000 4\5 executed in 'matlab' gives ans=1.2500 x = pi/2; y = sin(x) executed in 'matlab' gives y = 1 z = 0; w = exp(4*z)/5 executed in 'matlab" gives z= .2000 Note that many programmers will prefer to write the expression forw above in the format w = (exp(4*x))/5which gives the same result and is sometimes less confusing whenthe string of arithmetic operations is long. Using 'matlab', carryout some simple arithmetic operations with scalars you define. Indoing so utilize the 'matlab' functions sqrt(x), abs(s), sin(x),asin(x), atan(x), atan2(x), log(x), and log10(x) as well as exp(x).Many other functions are available in 'matlab' and can be found inthe documentation. Matrix Calculations. Because matrices are made up of a numberof elements and not a single number (except for the 1x1 scalarmatrix), the ordinary rules of commutative, associative anddistributive operations in arithmetic do not always follow.

Page 87: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 22 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

Moreover, a number of important but common-sense rules will prevailin matrix algebra and 'matlab' when dealing with nonscalarquantities. Addition and Subtraction of Matrices. Only matrices of the SAMEORDER can be added or subtracted. When two matrices of the sameorder are added or subtracted in matrix algebra, the individualelements are added or subtracted. Thus the distributive ruleapplies. A + B = B + A and A - B = B - A If C = A + B then each element Cij = Aij + Bij. Define A and B as follows: A=[1 2 3; 3 3 3; 5 3 1] B=[2 -3 4;2 -2 2; 0 4 0] Then note that C = A + B and C = B + Agives C = 3 -1 7 5 1 5 5 7 1 Now define the row vector x= [3 5 7] and the column vector y = [4; -1; -3] Note that the operation z = x + y is not valid! It is not valid because the two matrices do not havethe same order. (x is a 1x3 matrix and y is a 3x1 matrix.) Addingany number of 1x1 matrices or scalars is permissible and followsthe ordinary rules of arithmetic because the 1x1 matrix is ascalar. Adding two vectors is permissible so long as each is a rowvector (1xn matrix) or column vector (nx1 matrix). Of course anynumber of vectors can be added or subtracted, the result being thearithmetic sum of the individual elements in the column or rowvectors. Square matrices can always be added or subtracted so longas they are of the same order. A 4x4 square matrix can not be addedto a 3x3 square matrix, because they are not of the same order,although both matrices are square. Multiplication of Matrices. Matrix multiplication, though straight-forward in definition, is more complex than arithmeticmultiplication because each matrix contains a number of elements.Recall that with vector multiplication, the existence of a number

Page 88: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 23 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

of elements in the vector resulted in two concepts ofmultiplication, the scalar product and the vector product. Matrixmultiplication has its array of special rules as well. In matrix multiplication, the elements of the product, C, oftwo matrices A*B are calculated from Cij = ‘ Aik * Bkj To form this sum, the number of columns of the first or left matrix(A) must be equal to the number of rows in the second or rightmatrix (B). The resulting product, matrix C, has an order for whichthe number of rows equals the number of rows of the first (left)matrix (A) and the product (C) has a number of columns equal to thenumber of columns in the second (right) matrix (B). It is clearthat A*B IS NOT NECESSARILY EQUAL TO B*A! It is also clear thatA*B and B*A only exist for square matrices! Consider the simple product of two square 2x2 matrices. a = [ 1 2; 3 4]; b = [ 8 7; 6 5]; Calling the product c = a*b c11 = a11*b11 + a12*b21 c12 = a11*b12 + a12*b22 c21 = a21*b11 + a22*b21 c22 = a21*b12 + a22*b22 Carry out the calculations by hand and verify the result using'matlab'. Next, consider the following matrix product of a 3x2matrix X and a 2x4 matrix Y. X = [2 3 ; 4 -1 ; 0 7]; Y = [5 -6 7 2 ; 1 2 3 6]; First, note that the matrix product X*Y exists because X has thesame number of columns (2) as Y has rows (2). (Note that Y*X doesNOT exist!) If the product of X*Y is called C, the matrix C mustbe a 3x4 matrix. Again, carry out the calculations by hand andverify the result using 'matlab'. Note that the PRODUCT OF A SCALAR AND A MATRIX is a matrix inwhich every element of the matrix has been multiplied by thescalar. Verify this by recalling the matrix X defined above, andcarry out the product 3*X on 'matlab'. (Note that this can bewritten X*3 as well as 3*X, because quantity '3' is scalar.) ARRAY PRODUCTS Recall that addition and subtraction of matrices involvedaddition or subtraction of the individual elements of the matrices.Sometimes it is desired to simply multiply or divide each elementof an matrix by the corresponding element of another matrix. Theseare called 'array operations" in 'matlab'. Array or element-by-element operations are executed when the operator is preceded by a

Page 89: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 24 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

'.' (period). Thus a .* b multiplies each element of a by the respective element of b a ./ b divides each element of a by the respective element of b a .\ b divides each element of b by the respective element of a a .^ b raise each element of a by the respective b element For example, if matrices G and H are defined G = [ 1 3 5; 2 4 6]; H = [-4 0 3; 1 9 8]; G .* H = [ -4 0 15 2 36 48 ] TRANSPOSE OF A MATRIX The transpose of a matrix is obtained by interchanging therows and columns. The 'matlab' operator that creates the transposeis the single quotation mark, '. Recalling the matrix G G' = [ 1 2 3 4 5 6 ] Note that the transpose of a m x n matrix creates a n x m matrix.One of the most useful operations involving the transpose is thatof creating a column vector from a row vector, or a row vector froma column vector. INNER (SCALAR) PRODUCT OF TWO VECTORS The scalar or inner product of two row vectors, G1 and G2 isfound as follows. Create the row vectors for this example bydecomposing the matrix G defined above. G1 = G(1,:) G2 = G(2,:) Then the inner product of the 1x3 row vector G1 and the 1x3 rowvector G2 is G1 * G2' = 44 Verify this result by carrying out the operations on 'matlab'. If the two vectors are each column vectors, then the innerproduct must be formed by the matrix product of the transpose of acolumn vector times a column vector, thus creating an operation inwhich a 1 x n matrix is multiplied with a n x 1 matrix. In summary, note that the inner product must always be theproduct of a row vector times a column vector. OUTER PRODUCT OF TWO VECTORS

Page 90: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 25 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

If two row vectors exist, G1 and G2 as defined above, theouter product is simply G1' * G2 {Note G1' is 3x1 and G2 is 1x3} and the result is a square matrix in contrast to the scalar resultfor the inner product. DON'T CONFUSE THE OUTER PRODUCT WITH THEVECTOR PRODUCT IN MECHANICS! If the two vectors are columnvectors, the outer product must be formed by the product of onevector times the transpose of the second! OTHER OPERATIONS ON MATRICES As noted above, many functions that exist can be applieddirectly to a matrix by simply allowing the function to operate oneach element of the matrix array. This is true for thetrigonometric functions and their inverse. It is true also for theexponential function, ex, exp(), and the logarithmic functions,log() and log10(). Exponential operations (using ^) on matrices are quitedifferent from their use with scalars. If W is a square matrixW^2 implies W*W which is quite different from W.*W. Be certain ofyour intent before raising a matrix to an exponential power. Ofcourse W^2 only exists if W is a square matrix.SPECIAL MATRICES A number of special functions exist in 'matlab' to createspecial or unusual matrices. For example, matrices with elementvalues of zero or 1 are sometimes useful. zeros(4) creates a square matrix (4 x 4) whose elements are zero. zeros(3,2) creates a 3 row, 2 column matrix of zeros. Similarly the commands ones(4) creates a 4 x 4 square matrixwhose elements are 1's and 'ones(3,2)' creates a 3x2 matrix whoseelements are 1's. If a m x n matrix, say A, already exists, the command'ones(A)' creates an m x n matrix of 1's. The command 'zeros(A)'creates an mxn matrix of 0's. Note that these commands do notalter the previously defined matrix A, which is only a basis forthe size of the matrix created by commands zeros() and ones(). The identity matrix is a square matrix with 1's on thediagonal and 0's off the diagonal. Thus a 4x4 identity matrix, a,is a=[1 0 0 0 0 1 0 0

Page 91: Matlab Automotive QAs

1/14/10 11:00 AMA BRIEF LIST OF MATLAB COMMANDS

Page 26 of 26http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm

0 0 1 0 0 0 0 1] This matrix can be created with the 'eye' function. Thus, a = eye(4) The 'eye' function will create non-square matrices. Thus eye(3,2)creates 1 0 0 1 0 0and eye(2,3)creates 1 0 0 0 1 0 PRACTICE 1. The first four terms of the fourier series for the square wavewhose amplitude is 5 and whose period is 2ƒ is y = (20/ƒ)[sinx + (1/3)sin3x + (1/5)sin5x + (1/7)sin7x)] Calculate this series, term by term, and plot the results for eachpartial sum.

Page 92: Matlab Automotive QAs

Matlab Basics Commands

Vectors Functions Plotting Polynomials Matrices Printing Using M-files in Matlab Getting help in Matlab

Matlab is an interactive program for numerical computation and data visualization; it is used extensively by control engineers for analysis and design. There are many different toolboxes available which extend the basic functions of Matlab into different application areas; in these tutorials, we will make extensive use of the Control Systems Toolbox. Matlab is supported on Unix, Macintosh, and Windows environments; a student version of Matlab is available for personal computers. For more information on Matlab, contact the Mathworks.

The idea behind these tutorials is that you can view them in one window while running Matlab in another window. You should be able to re-do all of the plots and

Page 93: Matlab Automotive QAs

calculations in the tutorials by cutting and pasting text from the tutorials into Matlab or an m-file.

Vectors

Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between brackets, and set it equal to a variable. For example, to create the vector a, enter into the Matlab command window (you can "copy" and "paste" from your browser into Matlab to make it easy):

a = [1 2 3 4 5 6 9 8 7]

Matlab should return:

a = 1 2 3 4 5 6 9 8 7

Let's say you want to create a vector with elements between 0 and 20 evenly spaced in increments of 2 (this method is frequently used to create a time vector):

t = 0:2:20 t = 0 2 4 6 8 10 12 14 16 18 20

Manipulating vectors is almost as easy as creating them. First, suppose you would like to add 2 to each of the elements in vector 'a'. The equation for that looks like:

Page 94: Matlab Automotive QAs

b = a + 2 b = 3 4 5 6 7 8 11 10 9

Now suppose, you would like to add two vectors together. If the two vectors are the same length, it is easy. Simply add the two as shown below:

c = a + b c = 4 6 8 10 12 14 20 18 16

Subtraction of vectors of the same length works exactly the same way.

Functions

To make life easier, Matlab includes many standard functions. Each function is a block of code that accomplishes a specific task. Matlab contains all of the standard functions such as sin, cos, log, exp, sqrt, as well as many others. Commonly used constants such as pi, and i or j for the square root of -1, are also incorporated into Matlab.

sin(pi/4) ans = 0.7071

Page 95: Matlab Automotive QAs

To determine the usage of any function, type help [function name] at the Matlab command window. Matlab even allows you to write your own functions with the function command; follow the link to learn how to write your own functions and see a listing of the functions we created for this tutorial.

Plotting

It is also easy to create plots in Matlab. Suppose you wanted to plot a sine wave as a function of time. First make a time vector (the semicolon after each statement tells Matlab we don't want to see all the values) and then compute the sin value at each time.

t=0:0.25:7; y = sin(t); plot(t,y)

The plot contains approximately one period of a sine wave. Basic plotting is very easy in Matlab, and the

Page 96: Matlab Automotive QAs

plot command has extensive add-on capabilities. I would recommend you visit the plotting page to learn more about it.

Polynomials

In Matlab, a polynomial is represented by a vector. To create a polynomial in Matlab, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:

To enter this into Matlab, just enter it as a vector in the following manner

x = [1 3 -15 -2 9] x = 1 3 -15 -2 9

Matlab can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,

would be represented in Matlab as:

y = [1 0 0 0 1]

Page 97: Matlab Automotive QAs

You can find the value of a polynomial using the polyval function. For example, to find the value of the above polynomial at s=2,

z = polyval([1 0 0 0 1],2) z = 17

You can also extract the roots of a polynomial. This is useful when you have a high-order polynomial such as

Finding the roots would be as easy as entering the following command;

roots([1 3 -15 -2 9]) ans = -5.5745 2.5836 -0.7951 0.7860

Let's say you want to multiply two polynomials together. The product of two polynomials is found by taking the convolution of their coefficients. Matlab's function conv that will do this for you.

x = [1 2];

Page 98: Matlab Automotive QAs

y = [1 4 8]; z = conv(x,y) z = 1 6 16 16

Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the result. Let's divide z by y and see if we get x.

[xx, R] = deconv(z,y) xx = 1 2 R = 0 0 0 0

As you can see, this is just the polynomial/vector x from before. If y had not gone into z evenly, the remainder vector would have been something other than zero. If you want to add two polynomials together which have the same order, a simple z=x+y will work (the vectors x and y must have the same length). In the general case, the user-defined function, polyadd can be used. To use polyadd, copy the function into an m-file, and then use it just as you would any other function in the Matlab toolbox. Assuming you had the polyadd function stored as a m-file, and you wanted

Page 99: Matlab Automotive QAs

to add the two uneven polynomials, x and y, you could accomplish this by entering the command:

z = polyadd(x,y) x = 1 2 y = 1 4 8 z = 1 5 10

Matrices

Entering matrices into Matlab is the same as entering a vector, except each row of elements is separated by a semicolon (;) or a return:

B = [1 2 3 4;5 6 7 8;9 10 11 12] B = 1 2 3 4 5 6 7 8 9 10 11 12 B = [ 1 2 3 4

Page 100: Matlab Automotive QAs

5 6 7 8 9 10 11 12] B = 1 2 3 4 5 6 7 8 9 10 11 12

Matrices in Matlab can be manipulated in many ways. For one, you can find the transpose of a matrix using the apostrophe key:

C = B' C = 1 5 9 2 6 10 3 7 11 4 8 12

It should be noted that if C had been complex, the apostrophe would have actually given the complex conjugate transpose. To get the transpose, use .' (the two commands are the same if the matix is not complex). Now you can multiply the two matrices B and C together. Remember that order matters when multiplying matrices.

D = B * C

Page 101: Matlab Automotive QAs

D = 30 70 110 70 174 278 110 278 446 D = C * B D = 107 122 137 152 122 140 158 176 137 158 179 200 152 176 200 224

Another option for matrix manipulation is that you can multiply the corresponding elements of two matrices using the .* operator (the matrices must be the same size to do this).

E = [1 2;3 4] F = [2 3;4 5] G = E .* F E = 1 2 3 4 F = 2 3 4 5

Page 102: Matlab Automotive QAs

G = 2 6 12 20

If you have a square matrix, like E, you can also multiply it by itself as many times as you like by raising it to a given power.

E^3 ans = 37 54 81 118

If wanted to cube each element in the matrix, just use the element-by-element cubing.

E.^3 ans = 1 8 27 64

You can also find the inverse of a matrix: X = inv(E) X = -2.0000 1.0000 1.5000 -0.5000

or its eigenvalues:

Page 103: Matlab Automotive QAs

eig(E) ans = -0.3723 5.3723

There is even a function to find the coefficients of the characteristic polynomial of a matrix. The "poly" function creates a vector that includes the coefficients of the characteristic polynomial.

p = poly(E) p = 1.0000 -5.0000 -2.0000

Remember that the eigenvalues of a matrix are the same as the roots of its characteristic polynomial:

roots(p) ans = 5.3723 -0.3723

Page 104: Matlab Automotive QAs

Printing

Printing in Matlab is pretty easy. Just follow the steps illustrated below: Macintosh

To print a plot or a m-file from a Macintosh, just click on the plot or m-file, select Print under the File menu, and hit return.

Windows To print a plot or a m-file from a computer running Windows, just selct Print from the File menu in the window of the plot or m-file, and hit return.

Unix To print a plot on a Unix workstation enter the command: print -P<printername> If you want to save the plot and print it later, enter the command: print plot.ps Sometime later, you could print the plot using the command "lpr -P plot.ps" If you are using a HP workstation to print, you would instead use the command "lpr -d plot.ps" To print a m-file, just print it the way you would any other file, using the command "lpr -P <name of m-file>.m" If you are using a HP workstation to print, you would instead use the command "lpr -d plot.ps<name of m-file>.m"

Page 105: Matlab Automotive QAs

Using M-files in Matlab

There are slightly different things you need to know for each platform. Macintosh

There is a built-in editor for m-files; choose "New M-file" from the File menu. You can also use any other editor you like (but be sure to save the files in text format and load them when you start Matlab).

Windows Running Matlab from Windows is very similar to running it on a Macintosh. However, you need to know that your m-file will be saved in the clipboard. Therefore, you must make sure that it is saved as filename.m

Unix You will need to run an editor separately from Matlab. The best strategy is to make a directory for all your m-files, then cd to that directory before running both Matlab and the editor. To start Matlab from your Xterm window, simply type: matlab.

You can either type commands directly into matlab, or put all of the commands that you will need together in an m-file, and just run the file. If you put all of your m-files in the same directory that you run matlab from, then matlab will always find them.

Page 106: Matlab Automotive QAs

Getting help in Matlab

Matlab has a fairly good on-line help; type help command name

for more information on any given command. You do need to know the name of the command that you are looking for; a list of the all the ones used in these tutorials is given in the command listing; a link to this page can be found at the bottom of every tutorial and example page. Here are a few notes to end this tutorial. You can get the value of a particular variable at any time by typing its name. B B = 1 2 3 4 5 6 7 8 9 You can also have more that one statement on a single line, so long as you separate them with either a semicolon or comma. Also, you may have noticed that so long as you don't assign a variable a specific operation or result, Matlab with store it in a temporary variable called "ans".

User feedback

Page 107: Matlab Automotive QAs

We would like to hear about difficulties you had with the tutorials, suggestions you have for improvement, errors that you found, or any other comments that you have. This feedback is anonymous; include your email address if you want a reply.

Some Useful MATLAB Commands

First, the most important command in MATLAB:

>> help command_name Displays complete information about any command. Take note of any cross references at the end of each help entry. help with no command specified lists all categories of available commands. Note: helpwin brings up a separate gui help window -- useful if you're doing

Page 108: Matlab Automotive QAs

other things in the main window.

Interacting with MATLAB:

>> command >> command;

A semicolon after any command suppresses output from that command to the MATLAB window (but not, for example, to a figure) - especially useful if the output is a very long vector.

>> <UP ARROW> Recalls the last command entered. You can repeat it to go farther back, or press <DOWN ARROW> to scroll forward.

>> abc<UP ARROW> Recalls the last command entered that starts with "abc".

Page 109: Matlab Automotive QAs

>> more on >> more off

Turns on and off more, which displays all output (including help information) one screen at a time.

>> who Tells you what variables currently exist.

>> clear >> clear variable

Deletes all variables, or the specified variable.

>> format long g >> format compact

Displays variables (but not systems) with more digits. Does not affect storage or computation. Gets rid of the extra blank lines in the display.

Commands for making and formatting plots:

>> p1=plot(t1,y1); >> delete(p1)

Plots y1 vs. t1. Note that setting the plot equal to a name lets

Page 110: Matlab Automotive QAs

you delete it afterwards - useful if you're plotting several things in the same figure and make a mistake. y1 and t1 must be vectors of the same size.

>> plot(y(:,1),y(:,2)) Plots the second column of matrix y vs. the first column. See note at end of section.

>> subplot(m,n,p) Breaks the figure up into mxn separate graphs, and selects the pth one as current; if there are already mxn graphs, leaves graphs as they are and selects the pth one.

>> xlabel('label_text') >> ylabel('label_text') >> title('title_text')

Labels the axes or the entire subplot with specified text

Page 111: Matlab Automotive QAs

(note single quotes).

>> g1 = gtext('plot_text'); >> delete(g1)

Lets you place the given text (in single quotes) by clicking on the graph. Note that setting the gtext equal to a name lets you delete it afterwards.

>> grid Toggles on and off a grid superimposed over the current graph; you can also type grid on and grid off.

>> sgrid Draws a grid on a plot of the s plane (root locus plot or pole and zero locations), which consists of lines of constant damping coefficient (zeta) and natural frequency (wn).

Page 112: Matlab Automotive QAs

>> hold Toggles on and off the plot hold, which adds new plots to any already in the graph (without it, new plots delete previous ones). You can also type hold on and hold off.

>> axis([xmin xmax ymin ymax]) >> axis auto

Sets the limits of the x and y axes manually, or lets them be set automatically. There are also many other options available for axis.

>> zoom Lets you select an area of the plot (using the mouse) to zoom in on. Also, clicking the left mouse button once will zoom in, and clicking the right button will zoom out,

Page 113: Matlab Automotive QAs

by a factor of two. Double clicking the right mouse button returns to the original scale; typing zoom again turns off the zoom function.

>> [x, y] = ginput(n) >> [x, y] = ginput

Lets you input the coordinates of points on the graph with the mouse; collects n points and stores them in the vectors x and y, or if n is absent, keeps collecting points until you press <ENTER>.

Matrix and vector manipulation commands:

>> k=linspace(k1,k2) >> k=linspace(k1,k2,n)

Returns a vector of 100 (or, if specified, n) points equally spaced between x1 and x2.

Page 114: Matlab Automotive QAs

>> max(y) Returns the largest element in the vector y.

>> inv(A) Returns the inverse of the square, nonsingular matrix A.

>> det(A) Calculates the determinant of the matrix A.

>> eig(A) >> [V,D] = eig(A)

Returns the eigenvalues of A, or sets V to a matrix containing the eigenvectors of A and sets D to a diagonal matrix containing the corresponding eigenvalues.

>> rank(A) Returns the rank of any matrix A.

Commands useful in system analysis:

>> roots(f) Returns the roots of a polynomial, where f

Page 115: Matlab Automotive QAs

is a vector containing the coefficients of the polynomial.

>> conv(P1,P2) Multiplies two polynomials (P1 and P2 are vectors containing the coeffiecients of the polynomials) and returns the resulting coefficients. This is actually a convolution of the two vectors, which also works as coefficient multiplication.

>> sys1=tf(num,den) >> sys2=ss(A,B,C,D)

>> sys1=tf(sys2)

>> sys2=ss(sys1)

Creates a system, as a transfer function or state-space representation. Also converts between two different representations of a system. The zpk (zero/pole/gain) command works

Page 116: Matlab Automotive QAs

similarly.

>> [R,P,K]=residue(num,den) Finds the partial fraction expansion of a function H(s), where num is a vector containing the coefficients of the numerator, and den of the denominator, of H(s). Returns the numerators (R) and poles (P) of the partial fractions and the remaining polynomial (K): H(s) = R1/(s-P1) + R2/(s-P2) + ... + Rn/(s-Pn) + K(s).

>> sys3=series(sys1,sys2) Finds the result of putting Systems 1 and 2 in series, and returns either the resulting transfer function numerator and denominator or the resulting state

Page 117: Matlab Automotive QAs

space matrices. Mixing system descriptions will work.

>> sys3=feedback(sys1,sys2) >> sys2=feedback(sys1,tf(1,1))

Finds the result of adding System 2 as a feedback loop to System 1, assuming a negative feedback, and returns either the resulting transfer function numerator and denominator or the resulting state space matrices.

>> impulse(sys) >> step(sys)

Plots the impulse response or step response of the given system. Useful trick: if you have a Laplace transform F(s) of a time function f(t), plotting the impulse response of F(s) is the same as plotting

Page 118: Matlab Automotive QAs

f(t).

>> [y,t,x]=impulse(sys) >> [y,t,x]=step(sys)

Giving impusle and step output variables returns the output (y), time (t), and states(x) (if state space) vectors, which you can then plot or manipulate.

>> initial(sys,x0) Plots the behavior of the given state-space system with initial condition x0 and no input.

>> lsim(sys,u,t,x0) Plots the response of the given system to the input signal u(t). The initial condition x0 can be added for state-space systems.

>> bode(sys1,sys2,...) >> [mag.phase,w]=bode(sys,w) >> nyquist(sys)

Plots the Bode or Nyquist diagram for the given system(s). A plot is drawn if no

Page 119: Matlab Automotive QAs

>> {re,im,w]=nyquist(sys,w) return arguments. The frequency points may be specified in the vector w .

>> margin(sys) >> [gm,pm,wcg,wcp]=margin(sys)

Finds the gain margin and phase margin, and the frequencies at which they occur, of the given system. If run with no output arguments, margin also displays the Bode plot, with the margins marked on it and their values displayed in the figure title.

>> rlocus(sys,k) Plots the root locus for the given system, i.e. where den(s) + k*num(s) = 0 (or equivalent for the state space form). The vector of values for k is optional.

Page 120: Matlab Automotive QAs

>> rlocfind(sys) >> [k,poles]=rlocfind(sys)

Lets you select a pole location from a root locus plot using the mouse, and returns the value of k needed to give such a pole, as well as all the resulting pole locations in the vector poles (if present). rlocfind picks the point on the locus closest to the crosshairs; note that you must already have the root locus graphed to be able to see points you might want to pick.

>> sys2=canon(sys1,'form') Finds a canonical form of the given system; the argument "form" can be either "modal" or "companion" (in single quotes).

Page 121: Matlab Automotive QAs

>> rltool

Opens a tool for designing controllers using the root locus plots.