Sunteți pe pagina 1din 121

1. Howtoaddnoisetoanimage? Thefunctionnoise.m,nowinstalledonashlandtoo,addsGaussian,uniform,saltandpepper, additiveormultiplicativenoisetoanimage. Byusingthefunctionimnoisewecanaddnoiseintoanimage.Thesyntaxisimnoise(image,type ofnoise). 2. WhatcanweuseMatlabfor? Simplecalculations2.Plottingandanalyzingmathematicalrelationships(2Dand3D)3.List& MatrixOperations4.Writingscriptfiles(atypeofprogramming)5.Symbolicmanipulationof equations6.Advancedvisualization,animationandGUIinterfacetools Matlabistobeutilizedfordataextraction,dataanalysisanddataprocessing,itisfurtherutilized forsomestatisticaltasktoanalyzethebehaviorofthesystembyplotting.itisusedtogenerate stimulusforverificationofthesystem 3. Howtocallmatlabinbatchmode? Thiscanbedonefromthecommandlineorfromamakefile.Youneedascript(filename.m). Justtypeatthecommandline,orincludeinthemakefile:matlab<filename.mwherefilename.

ename.m canwritetodiskafigure,abinary,anasciifile,anythingyouwant. 4. ExplainTheMATLABmathematicalfunctionlibrary? Thisisavastcollectionofcomputationalalgorithmsrangingfromelementaryfunctionslikesum, sine,cosine,andcomplexarithmetic,tomoresophisticatedfunctionslikematrixinverse,matrix eigenvalues,Besselfunctions,andfastFouriertransforms 5. ExplainaboutstressanalysisinMatlab? Peopleworkingontheseareasasaaerospaceengineersshouldhavefamiliarityandexposureto NASTRANandMATLABwithknowledgeonspaceenvironmentandmodelingofflexible dynamics.Theseaerospaceengineerswillberesponsibletoconductstressanalysisonmetallic andcompositestructures.NASTRAN,IDEAD,OracleandPATRANproficiencylevelisrequired. Theirdutiesalsoincludeonaircraftwhicharemetallicandcompositestructures.Thisincludes andunderstandingofcontrolsurfacestiffnessandloopcalculations,finiteelementmodeling (FEM),fatiguetestingrequirementandanalysis.

6. ExplainTheMATLABApplicationProgramInterface(API)? ThisisalibrarythatallowsyoutowriteCandFortranprogramsthatinteractwithMATLAB.It includefacilitiesforcallingroutinesfromMATLAB(dynamiclinking),callingMATLABasa computationalengine,andforreadingandwritingMATfiles. 7. CanMATLABpassbyreference? Thisisreallytwoquestionsinone.Oneis"CanImodifyafunction'sinputargument?"This wouldsavememoryandsimplify programminginsomecases.Theanswerhereis"NO".Ifyoumodifytheinputargumentofa function,allyoudoismodifya copyoftheargumentlocaltothefunction.Theonlywaytomodifyvariablesfromafunctionis toreturntheresultwhen finished,asin bigstruct=addelement(bigstruct,5); Theotherquestionis:"Passbyvaluewastesmemoryandtime,sincecopiesofvariablesare made.HowcanIfixthis?"Here, theansweris"Yourassumptionisflawed,youdon'tneedto."MATLABusesaschemecalled "copyonwrite"tooptimizethis sortofthing.Basically,dataissharedbetweenvariableswheneverpossible,andatruecopyis madeonlywhenoneofthe variablesismodified.SoalthoughMATLAB'scallingconventionappearstobepassbyvalue,if youdon'tmodifytheinput variables,thedataisnevercopied. 8. HowtoaddnoisetoanimageinMatlab? Thefunctionnoise.m,nowinstalledonashlandtoo,addsGaussian,uniform,saltandpepper, additiveormultiplicativenoisetoanimage. 9. HowcanImakeMATLABusethefullwindowwidthfordisplayingmatrices? InR12(MATLAB6.0),thiscanbecontrolledviaapreference.SelecttheFile|Preferences... menuitem,andselectCommand WindowinthePreferencesdialogthatappears.IntheDisplaysection,there'sacheckbox labeledLimitmatrixdisplaywidth

toeightycolumns.UncheckingthatboxallowsmatrixdisplaystomakefulluseoftheCommand Window'swidth.[Uncheckedis thedefault.] StartingwithMATLABR12.1,userscanaccessthecurrentcommandwindowsizeusingtheroot propertyCommandWindowSize.That is,sz=get(0,'CommandWindowSize').InR12.0,thereisnowaytodothisunlessyoucall undocumentedCfunctionsfromaMEXfile. 10. WhydoesMATLABonlycalculateto4significantdigits? Itdoesn't.Itusesfulldoubleprecisionfloatingpointnumberstocalculateeverything.Bydefaultit onlyprintsafewdecimalplacestothescreen.Youcanchangethisusingthecommandformatlong. Typehelpformatformoreinformation. 11. Howtosavedefaultsettingsacrosssessions? ThekeyistocreateaSTARTUP.Mfile.Lookattheonlinehelpformoredetailedinstructionsspecific toyouroperatingsystem. 12. CanwerunMatlabwithoutgraphics? Sometimesyoumaywanttorunscriptswhichcontainplottingcommandswithoutdisplaying theplotsandwithoutgoingintothescripttocommentoutthecommands.Anexample:ifyou're workingfromhomeandit'stooslowtorungraphicsoverthenetwork.YoucanplayasimpleUNIXtrick: %setenvDISPLAY/dev/null%Matlab. 13. ExplainLaTeXinMatlab? MatlabalreadyhandlesnaturallysimpleLaTeXencodingsthatallowintroducingGreekletttersor modifyingthefontsizeandappearanceinplots. 14. ExplainTheMATLABworkingenvironment? ThisisthesetoftoolsandfacilitiesthatyouworkwithastheMATLABuserorprogrammer.It includesfacilitiesformanagingthevariablesinyourworkspaceandimportingandexportingdata.It alsoincludestoolsfordeveloping,managing,debugging,andprofilingMfiles,MATLAB's applications. 15. OnwhatmachinesMatlabshouldberun? Runitfromsthelens,andonlyifsthelensisdown,fromcher,orsayortiree.Itworksonother machinestoo,butsomeoftheothermachineshaveolderversionsoftheOSandcoredumpupon exitingfrommatlab.Someotherlocalmachineswithnewsetupsworkfine.Tryyourlocalmachine. Matlabisblockedfromrunningontheservers

16. LaTeXinMatlab: MatlabalreadyhandlesnaturallysimpleLaTeXencodingsthatallowintroducingGreekletttersor modifyingthefontsizeandappearanceinplots. 17. WhatisMATLAB? MATLABisacommercialsoftwarepackagewrittenbyTheMathWorks,Inc.Quotingfromtheirweb page:"Numericcomputation,technicalgraphicsandvisualization,andanintuitiveprogramming languageforapplicationsinengineeringandscience." MATLABisacompleteenvironmentforhighlevelprogramming,aswellasinteractivedataanalysis. MATLABexcelsatnumericalcomputations,especiallywhendealingwithvectorsormatricesofdata. SymbolicmathisavailablethroughanaddontoolboxthatusesaMaplekernel. 18. VectorizationWhatisthat?Howtodoit? Thinkingistermsoffullmatrices/vectorsandalsosomerelatedfunctionsforthat*Useoffilter(), whichworksbeautifullyforsometimeseriesmodels 19. HowtocorrectlyapplythegraphicspatchesinMatlab? OpenaLOCALMACHINEwindowandtype:xhost+ashland#Addthefollowingcodesequencejust beforetheplotcommandthatwasgivingyouproblems:figure;set(gcf,'renderer','zbuffer');[s,w]= unix('echo$DISPLAY');set(gcf,'XDisplay',w); 20. WhatistheFAQeditorialpolicy? ThisFAQisactivelymaintainedasawikidocumentonMATLABCentral.CurrentlytheMATLAB CentralFileReviewTeamhasaccountsthatallowthemtoedittheFAQ.EventhoughtheFAQis hostedatMATLABCentral,contentissuppliedandmaintainedbytheusercommunityofthe comp.softsys.matlabnewsgroup.ForofficialMATLABtechsupport,seeinsteadtheMATLAB support 21. CanwerunMatlabwithoutgraphics? Sometimesyoumaywanttorunscriptswhichcontainplottingcommandswithoutdisplayingthe plotsandwithoutgoingintothescripttocommentoutthecommands.Anexample:ifyou're workingfromhomeandit'stooslowtorungraphicsoverthenetwork.YoucanplayasimpleUNIX trick:%setenvDISPLAY/dev/null%matlab 22. Howtocallmatlabinbatchmode? Thiscanbedonefromthecommandlineorfromamakefile.Youneedascript(filename.m).Just typeatthecommandline,orincludeinthemakefile:matlab<filename.mwherefilename.mcan writetodiskafigure,abinary,anasciifile,anythingyouwant.

23. OnwhatmachinesMatlabshouldberun? Wewillrunitfromsthelens,andonlyifsthelensisdown,fromcher,orsayortiree.Itworksonother machinestoo,butsomeoftheothermachineshaveolderversionsoftheOSandcoredumpupon exitingfrommatlab.Someotherlocalmachineswithnewsetupsworkfine.Tryyourlocalmachine. Matlabisblockedfromrunningontheservers 24. VectorizationWhatisthatinMatlab?Howtodoit? Thinkingistermsoffullmatrices/vectorsandalsosomerelatedfunctionsforthat*Useoffilter(), whichworksbeautifullyforsometimeseriesmodels 25. WhatcanweuseMatlabfor? Simplecalculations2.Plottingandanalyzingmathematicalrelationships(2Dand3D)3.List&Matrix Operations4.Writingscriptfiles(atypeofprogramming)5.Symbolicmanipulationofequations6. Advancedvisualization,animationandGUIinterfacetools 26. HowtomodifytheMATLABpath? Easiestsolution:usethePATHTOOLGUI.Orifyouwantcommandlineaccess: SuggestedbyJoshuaStiff:Youcanuseaddpathtoadddirectoriesfromthecommandline,and path2rctowritethecurrentpathbackto`pathdef.m'.Ifyoudonothavewritepermissionsfor `pathdef.m',path2rccanwritetoadifferentfile,whichyoucanexecutefromyour`startup.m'. 27. ExplainHandleGraphicsinMatlab? ThisistheMATLABgraphicssystem.Itincludeshighlevelcommandsfortwodimensionaland threedimensionaldatavisualization,imageprocessing,animation,andpresentationgraphics.Italso includeslowlevelcommandsthatallowyoutofullycustomizetheappearanceofgraphicsaswellas tobuildcompleteGraphicalUserInterfacesonyourMATLABapplications. 28. ExplainTheMATLABlanguage? Thisisahighlevelmatrix/arraylanguagewithcontrolflowstatements,functions,datastructures, input/output,andobjectorientedprogrammingfeatures.Itallowsboth"programminginthesmall" torapidlycreatequickanddirtythrowawayprograms,and"programminginthelarge"tocreate completelargeandcomplexapplicationprograms 29. WhataretheMATLABSystemParts? TheMATLABsystemconsistsoffivemainparts: *TheMATLABlanguage. *TheMATLABworkingenvironment. *HandleGraphics. *TheMATLABmathematicalfunctionlibrary.

*TheMATLABApplicationProgramInterface(API).

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

CANINTERVIEWQUESTIONS: 1.WhatisCAN? Answer:1.CANisamultimasterbroadcastserialbusstandardforconnectingelectroniccontrol unit(ECUs). 2.Controllerareanetwork(CANorCANbus)isavehiclebusstandarddesignedtoallow microcontrollersadevicestocommunicatewitheachotherwithinavehiclewithoutahostcomputer. 3.CANisamessagebasedprotocol,designedspecicallyforautomotiveapplicationsbutnowalso usedinotherareassuchasindustrialautomationandmedicalequipment. 4.TheControllerAreaNetwork(CAN)busisaserialasynchronousbususedininstrumentation applicationsforindustriessuchasautomobiles 2.CANframeworks? Answer:SOF1Dominant ArbitrationField11bitIdentier,1bitRTR(or)11bit,1SRR,1IDE,18bit,1RTR ControlFieldIDE,r0,4bits(DLC) DataField(08)Bytes CRCField15bits,Delimiter(1bitrecessive) ACKField1bit,Delimiter(1bitrecessive) EOF7bitsrecessive IFS3bitsrecessive

1 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

TypesofframesData,remote,ErrorframeandOverloadframe TypesoferrorsACKerror,Biterror,Stuerror,Formerror,CRCerror Errorframe012superpositionags,8recessive(Delimiter) Overloadframe012superpositionags,8recessive(Delimiter) 3.WhyCANishaving120ohmsateachend? Answer:Tominimizethereectionreference,toreducenoise.Toensurethatreectiondoesnot causecommunicationfailure,thetransmissionlinemustbeterminated. 4.WhyCANismessageorientedprotocol? Answer:CANprotocolisamessagebasedprotocol,notanaddressbasedprotocol.Thismeansthat messagesarenottransmittedfromonenodetoanothernodebasedonaddresses.Embeddedinthe CANmessageitselfisthepriorityandthecontentsofthedatabeingtransmitted.Allnodesinthe systemreceiveeverymessagetransmittedonthebus(andwillacknowledgeifthemessagewas properlyreceived).Itisuptoeachnodeinthesystemtodecidewhetherthemessagereceivedshould beimmediatelydiscardedorkepttobeprocessed.Asinglemessagecanbedestinedforone particularnodetoreceive,ormanynodesbasedonthewaythenetworkandsystemaredesigned. Forexample,anautomotiveairbagsensorcanbeconnectedviaCANtoasafetysystemrouternode only.Thisrouternodetakesinothersafetysysteminformationandroutesittoallothernodesonthe safetysystemnetwork.Thenalltheothernodesonthesafetysystemnetworkcanreceivethelatest airbagsensorinformationfromtherouteratthesametime,acknowledgeifthemessagewasreceived properly,anddecidewhethertoutilizethisinformationordiscardit. 5.CANlogicwhatitfollows? Answer:WiredANDlogic 6.WhatisCANArbitration? Answer:CANArbitrationisnothingbutthenodetryingtotakecontrolontheCANbus. 7.HowCANwillfollowtheArbitration? Answer:CSMA/CD+AMP(ArbitrationonMessagePriority) Twobusnodeshavegotatransmissionrequest.ThebusaccessmethodisCSMA/CD+AMP(Carrier SenseMultipleAccesswithCollisionDetectionandArbitrationonMessagePriority).Accordingto thisalgorithmbothnetworknodeswaituntilthebusisfree(CarrierSense).Inthatcasethebusisfree bothnodestransmittheirdominantstartbit(MultipleAccess).Everybusnodereadsbackbitbybit fromthebusduringthecompletemessageandcomparesthetransmittedvaluewiththereceived value.Aslongasthebitsareidenticalfrombothtransmittersnothinghappens.Thersttimethere th wasadierenceinthisexamplethe7 bitofthemessagethearbitrationprocesstakesplace: NodeAtransmitsadominantlevel,nodeBtransmitsarecessivelevel.Therecessivelevelwillbe overwrittenbythedominantlevel.ThisisdetectedbynodeBbecausethetransmittedvalueisnot equaltothereceivedvalue(CollisionDetection).AtthispointoftimenodeBhaslostthearbitration,

2 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

stopsthetransmissionofanyfurtherbitimmediatelyandswitchestoreceivemode,becausethe messagethathaswonthearbitrationmustpossiblybeprocessedbythisnode(Arbitrationon MessagePriority) Forexample,considerthreeCANdeviceseachtryingtotransmitmessages: Device1address433(decimalor00110110001binary) Device2address154(00010011010) Device3address187(00010111011) Assumingallthreeseethebusisidleandbegintransmittingatthesametime,thisishowthe arbitrationworksout.Allthreedeviceswilldrivethebustoadominantstateforthestartofframe (SOF)andthetwomostsignicantbitsofeachmessageidentier.Eachdevicewillmonitorthebus anddeterminesuccess.Whentheywritebit8ofthemessageID,thedevicewritingmessageID433 willnoticethatthebusisinthedominantstatewhenitwastryingtoletitberecessive,soitwill assumeacollisionandgiveupfornow.Theremainingdeviceswillcontinuewritingbitsuntilbit5, thenthedevicewritingmessageID187willnoticeacollisionandaborttransmission.Thisleavesthe devicewritingmessageID154remaining.Itwillcontinuewritingbitsonthebusuntilcompleteoran errorisdetected.Noticethatthismethodofarbitrationwillalwayscausethelowestnumericalvalue messageIDtohavepriority.Thissamemethodofbitwisearbitrationandprioritizationappliestothe 18bitextensionintheextendedformataswell. 8.WhatisthespeedofCAN? Answer:40m@1Mbpsandifthecablelengthincreaseswilldecreasethespeed,duetoRLConthe cable. 9.Ifmastersends764andSlavesends744whichwillgetthearbitration? Answer:StartsfromMSB,rstnibbleissame,Mastersends7,slavesalsosends7themessagewith moredominantbitswillgainthearbitration,lowestthemessageidentierhigherthepriority. 10.StandardCANandExtendedCANdierence? Answer:Numberofidentierscanbeaccommodatedforstandardframeare2power11. Numberofidentiersmorecomparetobaseframe,forextendedframeare2power29. IDEbit1forextendedframe. IDEbit0forStandardframe. 11.Whatisbitstung? Answer:CANusesaNonReturntoZeroprotocol,NRZ5,withbitstung.Theideabehindbit stungistoprovideaguaranteededgeonthesignalsothereceivercanresynchronizewiththe transmitterbeforeminorclockdiscrepanciesbetweenthetwonodescancauseaproblem.With NRZ5thetransmittertransmitsatmostveconsecutivebitswiththesamevalue.Aftervebitswith thesamevalue(zeroorone),thetransmitterinsertsastubitwiththeoppositestate.

3 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

12.Whatistheuseofbitstung? Answer:LongNRZmessagescauseproblemsinreceivers Clockdriftmeansthatiftherearenoedges,receiverslosetrackofbits Periodicedgesallowreceivertoresynchronizetosenderclock 13.WhatarethefunctionsofCANtransceiver? Answer:Thetransceiverprovidesdierentialtransmitcapabilitytothebusanddierentialreceive capabilitytotheCANcontroller.Transceiverprovidesanadvancedinterfacebetweentheprotocol controllerandthephysicalbusinaControllerAreaNetwork(CAN)node. Typically,eachnodeinaCANsystemmusthaveadevicetoconvertthedigitalsignalsgeneratedby aCANcontrollertosignalssuitablefortransmissionoverthebuscabling(dierentialoutput).Italso providesabuerbetweentheCANcontrollerandthehighvoltagespikesthatcanbegeneratedon theCANbusbyoutsidesources(EMI,ESD,electricaltransients,etc.). ThecantransceiverisadevicewhichdetectsthesignallevelsthatareusedontheCANbustothe logicalsignallevelsrecognizedbyamicrocontroller. 14.FunctionalityofDatalinklayerinCAN? Answer:LLC(LogicalLinkControl)Overloadcontrol,notication,MessagelteringandRecovery managementfunctions. MAC(MediumAccessControl)Encapsulation/decapsulation,errordetectionandcontrol,stung anddestungandserialization/deserialization. 15.Whatismeantbysynchronization? Answer:Synchronizationistimekeepingwhichrequiresthecoordinationofeventstooperatea systeminunison. 16.WhatismeantbyHardsynchronizationandsoftsynchronization? Answer:HardSynchronizationtobeperformedateveryedgefromrecessivetodominantedge duringBusIdle.Additionally,HardSynchronizationisrequiredforeachreceivedSOFbit.AnSOF bitcanbereceivedbothduringBusIdle,andalsoduringSuspendTransmissionandattheendof InterframeSpace.AnynodedisablesHardSynchronizationifitsamplesanedgefromrecessiveto dominantorifitstartstosendthedominantSOFbit. Twotypesofsynchronizationaresupported: Hardsynchronizationisdonewithafallingedgeonthebuswhilethebusisidle,whichis interpretedasaStartofframe(SOF).ItrestartstheinternalBitTimeLogic. SoftsynchronizationisusedtolengthenorshortenabittimewhileaCANframeisreceived.

4 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

17.Whatisthedierencebetweenfunctionandphysicaladdressing? Answer:Functionaladdressingisanaddressingschemethatlabelsmessagesbasedupontheir operationcodeorcontent.Physicaladdressingisanaddressingschemethatlabelsmessagesbased uponthephysicaladdresslocationoftheirsourceand/ordestination(s). 18.WhathappensifIhavetosendmorethan8bytesofdata? Answer:TheJ1939standardhasdenedamethodofcommunicatingmorethan8bytesofdataby sendingthedatainpacketsasspeciedintheTransportProtocol(TP).TherearetwotypesofTP,one forbroadcastingthedata,andtheotherforsendingittoaspecicaddress. DTCconsistsof4componentsSPN,FMI,OCandCM. ADTCisacombinationoffourindependentelds:theSuspectParameterNumber(SPN)ofthe channelorfeaturethatcanhavefaults;aFailureModeIdentier(FMI)ofthespecicfault;the occurrencecount(OC)oftheSPN/FMIcombination;andtheSPNconversionmethod(CM)which tellsthereceivingmodehowtointerprettheSPN.Together,theSPN,FMI,OCandCMforma numberthatadiagnostictoolcanusetounderstandthefailurethatisbeingreported.

(http://automotivetechis.les.wordpress.com/2012/06 /clip_image002.jpg) Figure1Messageformat 19.WhatisKWP2000? Answer:KWP2000(ISO14230)isaDiagnosticcommunicationsstandard.Speciespossiblesystem congurationsusingtheK&Llines.As91412butlimitedtothephysicalcharacteristics.Species possiblesystemcongurationsusingtheK&Llines. 5Baudwakeupas91412 Newfastinitialisationmethod 20.WhatisOBDII? Answer:OnBoardDiagnosticsinanautomotivecontextisagenerictermreferringtoavehicles selfdiagnosticandreportingcapability 21.WhyDiagnosticStandards? Answer:Assystemsgotmorecomplexthelinkbetweencauseandsymptombecamelessobvious.
5 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Thismeantthatelectronicsystemshadtohavesomelevelofselfdiagnosisandtocommunicatetothe outsideworld.Initiallymanysystemsusedtheirownprotocolswhichmeantthatgarageshadto havealargenumberoftoolseventodiagnoseasinglevehicle. 22.Whatismeantbyvericationandvalidation?? Answer:VericationandValidation(V&V)istheprocessofcheckingthatasoftwaresystemmeets specicationsandthatitfulllsitsintendedpurpose.Itisnormallypartofthesoftwaretesting processofaproject. AccordingtotheCapabilityMaturityModel(CMMISWv1.1), Verication:Theprocessofevaluatingsoftwaretodeterminewhethertheproductsofagiven developmentphasesatisfytheconditionsimposedatthestartofthatphase. Validation:Theprocessofevaluatingsoftwareduringorattheendofthedevelopmentprocessto determinewhetheritsatisesspeciedrequirements. Vericationshowsconformancewithspecication;validationshowsthattheprogrammeetsthe customersneeds 23.Canyouhavetwotransmittersusingthesameexactheadereld? Answer:Nothatwouldproduceabusconict Unlessyouhavemiddlewarethatensuresonlyonenodecantransmitatatime Forexampleusealowprioritymessageasatokentoemulatetokenpassing 24.CANphysicallayervoltagelevels

(http://automotivetechis.les.wordpress.com/2012/06/can1.jpg) 25.CANbittiming: AccordingtotheCANspecication,thebittimeisdividedintofoursegments.TheSynchronization Segment,thePropagationTimeSegment,thePhaseBuerSegment1,andthePhaseBuerSegment

6 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

2.Eachsegmentconsistsofaspecic,programmablenumberoftimequanta(seeTable1).Thelength ofthetimequantum(tq),whichisthebasictimeunitofthebittime,isdenedbytheCAN controllerssystemclockfsysandtheBaudRatePrescaler(BRP):tq=BRP/fsys.Typicalsystem clocksare:fsys=foscorfsys=fosc/2. TheSynchronizationSegmentSync_SegisthatpartofthebittimewhereedgesoftheCANbuslevel areexpectedtooccur;thedistancebetweenanedgethatoccursoutsideofSync_SegandtheSync_Seg iscalledthephaseerrorofthatedge.ThePropagationTimeSegmentProp_Segisintendedto compensateforthephysicaldelaytimeswithintheCANnetwork.ThePhaseBuerSegments Phase_Seg1andPhase_Seg2surroundtheSamplePoint.The(Re)SynchronizationJumpWidth(SJW) deneshowfararesynchronizationmaymovetheSamplePointinsidethelimitsdenedbythe PhaseBuerSegmentstocompensateforedgephaseerrors.

(http://automotivetechis.les.wordpress.com/2012/06/untitle436d.jpg) Twotypesofsynchronizationexist:HardSynchronizationandResynchronization.AHard Synchronizationisdoneonceatthestartofaframe;insideaframeonlyResynchronizationsoccur. HardSynchronizationAfterahardsynchronization,thebittimeisrestartedwiththeendof Sync_Seg,regardlessoftheedgephaseerror.Thushardsynchronizationforcestheedgewhichhas causedthehardsynchronizationtoliewithinthesynchronizationsegmentoftherestartedbittime. BitResynchronizationResynchronizationleadstoashorteningorlengtheningofthebittimesuch thatthepositionofthesamplepointisshiftedwithregardtotheedge. 26.FormulaforBaudratecalculation? Thebaudrateiscalculatedas:

baudrate(bitspersecond)=18.432x10^6/BRP/(1+TSEG1+TSEG2)

27.WhathappenwhentwoCANnodesaresendingsameidentieratasametime? Twonodesonthenetworkarenotallowedtosendmessageswiththesameid.Iftwonodestryto sendamessagewiththesameidatthesametimearbitrationwillnotwork.Instead,oneofthe transmittingnodeswilldetectthathismessageisdistortedoutsideofthearbitrationeld.Thenodes

7 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

willthenusetheerrorhandlingofCAN,whichinthiscaseultimatelywillleadtooneofthe transmittingnodebeingswitchedo(busomode). 28.whatisthedierencebetweenBitRateandBaudRate? ThedierencebetweenBitandBaudrateiscomplicatedandintertwining.Botharedependentand interrelated.ButthesimplestexplanationisthataBitRateishowmanydatabitsaretransmittedper second.AbaudRateisthenumberoftimespersecondasignalinacommunicationschannel changes.Bitratesmeasurethenumberofdatabits(thatis0sand1s)transmittedinonesecondina communicationchannel.Agureof2400bitspersecondmeans2400zerosoronescanbetransmitted inonesecond,hencetheabbreviationbps.Individualcharacters(forexamplelettersornumbers) thatarealsoreferredtoasbytesarecomposedofseveralbits.Abaudrateisthenumberoftimesa signalinacommunicationschannelchangesstateorvaries.Forexample,a2400baudratemeansthat thechannelcanchangestatesupto2400timespersecond.Thetermchangestatemeansthatitcan changefrom0to1orfrom1to0uptoX(inthiscase,2400)timespersecond.Italsoreferstothe actualstateoftheconnection,suchasvoltage,frequency,orphaselevel).Themaindierencebetween thetwoisthatonechangeofstatecantransmitonebit,or slightlymoreorlessthanonebit,thatdependsonthe modulationtechniqueused.Sothebitrate(bps)andbaud rate(baudpersecond)havethisconnection:bps=baudper secondxthenumberofbitperbaudThemodulation techniquedeterminesthenumberofbitperbaud.Hereare twoexamples:WhenFSK(FrequencyShiftKeying,a transmissiontechnique)isused,eachbaudtransmitsone bit.Onlyonechangeinstateisrequiredtosendabit.Thus, themodemsbpsrateisequaltothebaudrate.Whena baudrateof2400isused,amodulationtechniquecalled phasemodulationthattransmitsfourbitsperbaudisused. So:2400baudx4bitsperbaud=9600bpsSuchmodemsarecapableof9600bpsoperation. CInterviewQuestions: 1.Whatisthedierencebetweendeclarationanddenition? Answer:Denitionmeanswhereavariableorfunctionisdenedinrealityandactualmemoryis allocatedforvariableorfunction. Declarationmeansjustgivingareferenceofavariableandfunction. 2.WhatarethedierentstorageclassesinC? Answer:AUTO,STATIC,EXTERN,REGISTER autoisthedefaultstorageclassforlocalvariables. { intCount; autointMonth;

8 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

} registerisusedtodenelocalvariablesthatshouldbestoredinaregisterinsteadofRAMThis meansthatthevariablehasamaximumsizeequaltotheregistersize(usuallyoneword)andcannot havetheunary&operatorappliedtoit(asitdoesnothaveamemorylocation).

{ registerintMiles; }

Registershouldonlybeusedforvariablesthatrequirequickaccesssuchascounters.Itshouldalso benotedthatdeningregistergoesnotmeanthatthevariablewillbestoredinaregister.Itmeans thatitMIGHTbestoredinaregisterdependingonhardwareandimplementationrestrictions. staticStorageClass staticisthedefaultstorageclassforglobalvariables.Thetwovariablesbelow(countandroad)both haveastaticstorageclass. staticintCount;intRoad;main(){printf(%d\n,Count);printf(%d\n,Road);} staticcanalsobedenedwithinafunction.Ifthisisdone,thevariableisinitalizedatcompilation timeandretainsitsvaluebetweencalls.Becauseitisinitializedatcompilationtime,theinitialization valuemustbeaconstant.Thisisseriousstutreadwithcare. voidFunc(void){staticCount=1;} Hereisanexample Thereisoneveryimportantuseforstatic.Considerthisbitofcode. char*Func(void);main(){char*Text1;Text1=Func();}char*Func(void){charText2[10]=martin; return(Text2);} FuncreturnsapointertothememorylocationwhereText2startsBUTText2hasastorageclass ofautoandwilldisappearwhenweexitthefunctionandcouldbeoverwrittenbysomethingelse. Theansweristospecify: staticcharText[10]=martin; ThestorageassignedtoText2willremainreservedforthedurationiftheprogram. externstorageClass externdenesaglobalvariablethatisvisabletoALLobjectmodules.Whenyouuseexternthe variablecannotbeinitalizedasallitdoesispointthevariablenameatastoragelocationthathas beenpreviouslydened.

9 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Source1Source2 externintcount;intcount=5; write()main() {{ printf(countis%d\n,count);write(); }} Countinsource1willhaveavalueof5.Ifsource1changesthevalueofcountsource2willseethe newvalue.Herearesomeexamplesourceles. 3.Whatisinterrupt? Answer:Interrupts(alsoknownastrapsorexceptionsinsomeprocessors)areatechniqueof divertingtheprocessorfromtheexecutionofthecurrentprogramsothatitmaydealwithsome eventthathasoccurred.Suchaneventmaybeanerrorfromaperipheral,orsimplythatanI/O devicehasnishedthelasttaskitwasgivenandisnowreadyforanother.Aninterruptisgenerated inyourcomputereverytimeyoutypeakeyormovethemouse.Youcanthinkofitasahardware generatedfunctioncall. 4.WhatisHardwareInterrupt? Answer:TherearetwowaysoftellingwhenanI/Odevice(suchasaserialcontrolleroradisk controller)isreadyforthenextsequenceofdatatobetransferred.Therstisbusywaitingorpolling, wheretheprocessorcontinuouslychecksthedevicesstatusregisteruntilthedeviceisready.This wastestheprocessorstimebutisthesimplesttoimplement.Forsometimecriticalapplications, pollingcanreducethetimeittakesfortheprocessortorespondtoachangeofstateinaperipheral. 5.WhatisSoftwareInterrupt? Answer:Asoftwareinterruptisgeneratedbyaninstruction.Itisthelowestpriorityinterruptandis generallyusedbyprogramstorequestaservicetobeperformedbythesystemsoftware(operating systemorrmware). DierencebetweenHardwareInterruptandSoftwareInterrupt Aninterruptisaspecialsignalthatcausesthecomputerscentralprocessingunittosuspendwhatit isdoingandtransfersitscontroltoaspecialprogramcalledaninterrupthandler.Theresponsibility ofaninterrupthandleristodeterminewhatcausedtheinterrupt,servicetheinterruptandthen returnthecontroltothepointfromwheretheinterruptwascaused.Thedierence betweenhardwareinterruptandsoftwareinterruptisasbelow: HardwareInterrupt:ThisinterruptiscausedbysomeexternaldevicesuchasrequesttostartanI/O

10 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

oroccurrenceofahardwarefailure. SoftwareInterrupt:ThisinterruptcanbeinvokedwiththehelpofINTinstruction.Aprogrammer triggeredthiseventthatimmediatelystopsexecutionoftheprogramandpassesexecutionovertothe INThandler.TheINThandlerisusuallyapartoftheoperatingsystemanddeterminestheactionto betakene.g.outputtothescreen,executeleetc. Thusasoftwareinterruptasitsnamesuggestsisdrivenbyasoftwareinstructionandahardware interruptistheresultofexternalcauses. 6.WhatisInterruptlatency?Howdoyoumeasureinterruptlatency?Howtoreducetheinterrupt latency? Answer:Interruptlatencyisthetimebetweeninterruptrequestandexecutionofrstinstructionof theISR. Weneedaoscilloscopeoralogicstateanalyzer.Byenteringtheinterruptserviceroutine(ISR),you needtoactivateanavailableportonyourhardware(likealedportorsoon)anddeactivateitjust beforereturningfromtheISR.Youcandothatbywritingtheappropriatecode. Byconnectingoneinputoftheoscilloscope(orlogicstateanalyzer)totheINTRpinofthe microprocessorandthesecondonetotheportyouactivate/deactivate,youcanmeasurethelatency timeandthedurationoftheISR Causesofinterruptlatencies Therstdelayistypicallyinthehardware:Theinterruptrequestsignalneedstobesynchronized totheCPUclock.Dependingonthesynchronizationlogic,typicallyupto3CPUcyclescanbelost beforetheinterruptrequesthasreachedtheCPUcore. TheCPUwilltypicallycompletethecurrentinstruction.Thisinstructioncantakealotofcycles; onmostsystems,divide,pushmultipleormemorycopyinstructionsaretheinstructionswhich requiremostclockcycles.OntopofthecyclesrequiredbytheCPU,thereareinmostcases additionalcyclesrequiredformemoryaccess.InanARM7system,theinstructionSTMDB SP!,{R0R11,LR};Pushparametersandperm.Registersistypicallytheworstcaseinstruction.It stores1332bitregistersonthestack.TheCPUrequires15clockcycles.Thememorysystemmay requireadditionalcyclesforwaitstates. Aftercompletionofthecurrentinstruction,theCPUperformsamodeswitchorpushesregisters (typicallyPCandagregisters)onthestack.Ingeneral,modernCPUs(suchasARM)performa modeswitch,whichrequireslessCPUcyclesthansavingregisters. Pipelinell:MostmodernCPUsarepipelined.Executionofaninstructionhappensinvarious stagesofthepipeline.Aninstructionisexecutedwhenithasreacheditsnalstageofthepipeline. Sincethemodeswitchhasushedthepipeline,afewextracyclesarerequiredtorellthe pipeline. 7.Vonneumanandharvardarchitecturedierences? Answer:ThenameHarvardArchitecturecomesfromtheHarvardMarkIrelaybasedcomputer.The mostobviouscharacteristicoftheHarvardArchitectureisthatithasphysicallyseparatesignalsand storageforcodeanddatamemory.Itispossibletoaccessprogrammemoryanddatamemory

11 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

simultaneously.Typically,code(orprogram)memoryisreadonlyanddatamemoryisreadwrite. Therefore,itisimpossibleforprogramcontentstobemodiedbytheprogramitself. ThevonneumannArchitectureisnamedafterthemathematicianandearlycomputerscientistJohn vonNeumann.vonNeumannmachineshavesharedsignalsandmemoryforcodeanddata.Thus, theprogramcanbeeasilymodiedbyitselfsinceitisstoredinreadwritememory. Harvardarchitecturehasseparatedataandinstructionbusses,allowingtransferstobeperformed simultaneouslyonbothbuses.VonNeumannarchitecturehasonlyonebuswhichisusedforboth datatransfersandinstructionfetches,andthereforedatatransfersandinstructionfetchesmustbe scheduledtheycannotbeperformedatthesametime. ItispossibletohavetwoseparatememorysystemsforaHarvardarchitecture.Aslongasdataand instructionscanbefedinatthesametime,thenitdoesntmatterwhetheritcomesfromacacheor memory.Butthereareproblemswiththis.Compilersgenerallyembeddata(literalpools)withinthe code,anditisoftenalsonecessarytobeabletowritetotheinstructionmemoryspace,forexamplein thecaseofselfmodifyingcode,or,ifanARMdebuggerisused,tosetsoftwarebreakpointsin memory.Iftherearetwocompletelyseparate,isolatedmemorysystems,thisisnotpossible.There mustbesomekindofbridgebetweenthememorysystemstoallowthis. Usingasimple,uniedmemorysystemtogetherwithaHarvardarchitectureishighlyinecient. Unlessitispossibletofeeddataintobothbusesatthesametime,itmightbebettertouseavon Neumannarchitectureprocessor. Useofcaches Athigherclockspeeds,cachesareusefulasthememoryspeedisproportionallyslower.Harvard architecturestendtobetargetedathigherperformancesystems,andsocachesarenearlyalways usedinsuchsystems. VonNeumannarchitecturesusuallyhaveasingleuniedcache,whichstoresbothinstructionsand data.Theproportionofeachinthecacheisvariable,whichmaybeagoodthing.Itwouldinprinciple bepossibletohaveseparateinstructionanddatacaches,storingdataandinstructionsseparately. Thisprobablywouldnotbeveryusefulasitwouldonlybepossibletoeveraccessonecacheata time. CachesforHarvardarchitecturesareveryuseful.Suchasystemwouldhaveseparatecachesforeach bus.TryingtouseasharedcacheonaHarvardarchitecturewouldbeveryinecientsincethenonly onebuscanbefedatatime.Havingtwocachesmeansitispossibletofeedbothbuses simultaneously.exactlywhatisnecessaryforaHarvardarchitecture. Thisalsoallowstohaveaverysimpleuniedmemorysystem,usingthesameaddressspaceforboth instructionsanddata.Thisgetsaroundtheproblemofliteralpoolsandselfmodifyingcode.Whatit doesmean,however,isthatwhenstartingwithemptycaches,itisnecessarytofetchinstructionsand datafromthesinglememorysystem,atthesametime.Obviously,twomemoryaccessesareneeded thereforebeforethecorehasallthedataneeded.Thisperformancewillbenobetterthanavon Neumannarchitecture.However,asthecachesllup,itismuchmorelikelythattheinstructionor datavaluehasalreadybeencached,andsoonlyoneofthetwohastobefetchedfrommemory.The othercanbesupplieddirectlyfromthecachewithnoadditionaldelay.Thebestperformanceis

12 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

achievedwhenbothinstructionsanddataaresuppliedbythecaches,withnoneedtoaccessexternal memoryatall. ThisisthemostsensiblecompromiseandthearchitectureusedbyARMsHarvardprocessorcores. Twoseparatememorysystemscanperformbetter,butwouldbediculttoimplement 8.RISCandCISCdierences? Answer: CISC:(ComplexInstructionSetComputer) Eg:IntelandAMDCPUs CISCchipshavealargeamountofdierentandcomplexinstructions. CISCchipsarerelativelyslow(comparedtoRISCchips)perinstruction,butuselittle(lessthan RISC)instructions. CISCarchitectureistocompleteataskinasfewlinesofassemblyaspossible.Thisisachievedby buildingprocessorhardwarethatiscapableofunderstandingandexecutingaseriesof operations. InCISC,compilerhastodoverylittleworktotranslateahighlevellanguagestatementinto assembly.Becausethelengthofthecodeisrelativelyshort,verylittleRAMisrequiredtostore instructions.Theemphasisisputonbuildingcomplexinstructionsdirectlyintothehardware. Whenexecuted,thisinstructionloadsthetwovaluesintoseparateregisters,multipliesthe operandsintheexecutionunit,andthenstorestheproductintheappropriateregister. RISC:(ReducedInstructionSetComputer) Eg:Apple,ARMprocessors Fewer,simplerandfasterinstructionswouldbebetter,thanthelarge,complexandslowerCISC instructions.However,moreinstructionsareneededtoaccomplishatask. RISCchipsrequirefewertransistors,whichmakesthemeasiertodesignandcheapertoproduce. itseasiertowritepowerfuloptimizedcompilers,sincefewerinstructionsexist. RISCischeaperandfaster. RISCputsagreaterburdenonthesoftware.Softwareneedstobecomemorecomplex.Software developersneedtowritemorelinesforthesametasks.ThereforetheyarguethatRISCisnotthe architectureofthefuture,sinceconventionalCISCchipsarebecomingfasterandcheaper Simpleinstructionsthatcanbeexecutedwithinoneclockcycle. MULTcommanddescribedabovecouldbedividedintothreeseparatecommands:LOAD, whichmovesdatafromthememorybanktoaregister,PROD,whichndstheproductoftwo operandslocatedwithintheregisters,andSTORE,whichmovesdatafromaregistertothe memorybanks. Atrst,thismayseemlikeamuchlessecientwayofcompletingtheoperation.Becausethere aremorelinesofcode,moreRAMisneededtostoretheassemblylevelinstructions.Thecompiler mustalsoperformmoreworktoconvertahighlevellanguagestatementintocodeofthisform. SeparatingtheLOADandSTOREinstructionsactuallyreducestheamountofworkthatthe computermustperform. MajorproblemofRISCtheydontaordthewidespreadcompatibility,thatx86chipsdo.

13 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

CISC Emphasisonhardware Includesmulticlock complexinstructions Memorytomemory: LOADandSTORE incorporatedininstructions Smallcodesizes, highcyclespersecond Transistorsusedforstoring complexinstructions CISC Complexinstructionsrequiremultiplecycles Manyinstructionscanreferencememory RISC

RISC Emphasisonsoftware Singleclock, reducedinstructiononly Registertoregister: LOADandSTORE areindependentinstructions Lowcyclespersecond, largecodesizes Spendsmoretransistors onmemoryregisters

Reducedinstructionstake1 cycle OnlyLoadandStore instructionscanreference memory Usespipeliningtoexecute instructions Manygeneralregisters

Instructionsareexecutedoneatatime Fewgeneralregisters 9.Whatarethestartupcodesteps? Answer: 1. 2. 3. 4. 5. 6. Disablealltheinterrupts. CopyandinitializeddatafromROMtoRAM. Zerotheuninitializeddataarea. Allocatespaceandforinitializethestack. Initializetheprocessorstackpointer Callmain

10.WhatarethebootingstepsforaCPU? Answer: ThepowersupplydoesaselfcheckandsendsapowergoodsignaltotheCPU. TheCPUstartsexecutingthecodestoredinROMonthemotherboardstartstheaddress0xFFFF0. TheroutinesinROMtestthecentralhardware,searchforvideoROM,performachecksumonthe videoROMandexecutestheroutinesinvideoROM. TheroutinesinthemotherboardROMthencontinuesearchingforanyROM,checksumand

14 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

executestheseroutines. AfterperformingthePOST(PowerOnSelfTest)isexecuted.Thesystemwillsearchforaboot device. Assumingthatthevalidbootdeviceisfound,IO.SYSisloadedintomemoryandexecuted.IO.SYS consistsprimarilyofinitializationcodeandextensiontothememoryboardROMBIOS. MSDOS.SYSisloadedintomemoryandexecuted.MSDOS.SYScontainstheDOSroutines. CONFIG.SYS(createdandmodiedbytheuser.loadadditionaldevicedriversforperipheral devices),COMMAND.COM(ItiscommandinterpreterIttranslatesthecommandsenteredby theuser.ItalsocontainsinternalDOScommands.ItexecutesandAUTOEXEC.BAT), AUTOEXEC.BAT(Itcontainsallthecommandsthattheuserwantswhichareexecuted automaticallyeverytimethecomputedisstarted). 11.WhatLittleEndianandBigEndian?HowcanIdeterminewhetheramachinesbyteorderis bigendianorlittleendian?Howcanweconvertfromonetoanother? Firstofall,DoyouknowwhatLittleEndianandBigEndianmean? LittleEndianmeansthatthelowerorderbyteofthenumberisstoredinmemoryatthelowest address,andthehigherorderbyteisstoredatthehighestaddress.Thatis,thelittleendcomesrst. Forexample,a4byte,32bitintegerByte3Byte2Byte1Byte0willbearrangedinmemoryas follows:Base_Address+0Byte0 Base_Address+1Byte1 Base_Address+2Byte2 Base_Address+3Byte3IntelprocessorsuseLittleEndianbyteorder.BigEndianmeansthatthe higherorderbyteofthenumberisstoredinmemoryatthelowestaddress,andthelowerorderbyte atthehighestaddress.Thebigendcomesrst.Base_Address+0Byte3 Base_Address+1Byte2 Base_Address+2Byte1 Base_Address+3Byte0Motorola,SolarisprocessorsuseBigEndianbyteorder.InLittleEndian form,codewhichpicksupa1,2,4,orlongerbytenumberproceedinthesamewayforallformats. Theyrstpickupthelowestorderbyteatoset0andproceedfromthere.Also,becauseofthe1:1 relationshipbetweenaddressosetandbytenumber(oset0isbyte0),multipleprecision mathematicroutinesareeasytocode.InBigEndianform,sincethehighorderbytecomesrst,the codecantestwhetherthenumberispositiveornegativebylookingatthebyteatosetzero.Itsnot requiredtoknowhowlongthenumberis,nordoesthecodehavetoskipoveranybytestondthe bytecontainingthesigninformation.Thenumbersarealsostoredintheorderinwhichtheyare printedout,sobinarytodecimalroutinesareparticularlyecient.Hereissomecodetodetermine whatisthetypeofyourmachine. intnum=1; if(*(char*)&num==1) { printf(\nLittleEndian\n); } else { printf(BigEndian\n); }AndhereissomecodetoconvertfromoneEndiantoanother.intmyreversefunc(intnum) { intbyte0,byte1,byte2,byte3;byte0=(num&x000000FF)>>0;
15 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

byte1=(num&x0000FF00)>>8; byte2=(num&x00FF0000)>>16; byte3=(num&xFF000000)>>24;return((byte0<<24)|(byte1<<16)|(byte2<<8)|(byte3<<0)); } 12.Programtondifamachineisbigendianorlittleendian? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 #include"stdio.h" #defineBIG_ENDIAN0 #defineLITTLE_ENDIAN1 intmain() { intvalue; value=endian(); if(value==1) printf("Machineislittleendian\n",value); else printf("MachineisBigEndian\n",value); } intendian(){ shortintword=0x0001; char*byte=(char*)&word; return(byte[0]?LITTLE_ENDIAN:BIG_ENDIAN); }

13.Swap2variableswithoutusingtemporaryvariable! a=a+b b=ab a=ab 14.WriteaprogramtogeneratetheFibonacciSeries? #include<stdio.h> #include<conio.h> main() { intn,i,c,a=0,b=1; printf(EnterFibonacciseriesofnthterm:); scanf(%d,&n); printf(%d%d,a,b); for(i=0;i<=(n3);i++) {

16 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

c=a+b; a=b; b=c; printf(%d,c); } getch(); }Output: EnterFibonacciseriesofnthterm:7 0112358 15.Writeaprogramtonduniquenumbersinanarray? 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.WriteaCprogramtoprintEquilateralTriangleusingnumbers? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 /*CprogramtoprintEquilateralTriangle*/ #include<stdio.h> main() { inti,j,k,n; printf("Enternumberofrowsofthetriangle\n"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=ni;j++) { printf(""); } for(k=1;k<=(2*i)1;k++)

17 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

17 18 19 20 21 22

{ printf("i"); } printf("\n"); } getch();

17.Writeaprogramfordeletionandinsertionofanodeinsinglelinkedlist? #include<stdio.h> #include<stdlib.h> typedefstructNode { intdata; structNode*next; }node; voidinsert(node*pointer,intdata) { /*Iteratethroughthelisttillweencounterthelastnode.*/ while(pointer>next!=NULL) { pointer=pointer>next; } /*Allocatememoryforthenewnodeandputdatainit.*/ pointer>next=(node*)malloc(sizeof(node)); pointer=pointer>next; pointer>data=data; pointer>next=NULL; } intnd(node*pointer,intkey) { pointer=pointer>next;//Firstnodeisdummynode. /*Iteratethroughtheentirelinkedlistandsearchforthekey.*/ while(pointer!=NULL) { if(pointer>data==key)//keyisfound. { return1; } pointer=pointer>next;//Searchinthenextnode. } /*Keyisnotfound*/ return0; }

18 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

voiddelete(node*pointer,intdata) { /*Gotothenodeforwhichthenodenexttoithastobedeleted*/ while(pointer>next!=NULL&&(pointer>next)>data!=data) { pointer=pointer>next; } if(pointer>next==NULL) { printf(Element%disnotpresentinthelist\n,data); return; } /*Nowpointerpointstoanodeandthenodenexttoithastoberemoved*/ node*temp; temp=pointer>next; /*temppointstothenodewhichhastoberemoved*/ pointer>next=temp>next; /*Weremovedthenodewhichisnexttothepointer(whichisalsotemp)*/ free(temp); /*Beacusewedeletedthenode,wenolongerrequirethememoryusedforit. free()willdeallocatethememory. */ return; } voidprint(node*pointer) { if(pointer==NULL) { return; } printf(%d,pointer>data); print(pointer>next); } intmain() { /*startalwayspointstotherstnodeofthelinkedlist. tempisusedtopointtothelastnodeofthelinkedlist.*/ node*start,*temp; start=(node*)malloc(sizeof(node)); temp=start; temp>next=NULL; /*Hereinthiscode,wetaketherstnodeasadummynode. Therstnodedoesnotcontaindata,butitusedbecausetoavoidhandlingspecialcases ininsertanddeletefunctions. */ printf(1.Insert\n); printf(2.Delete\n); printf(3.Print\n);
19 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

printf(4.Find\n); while(1) { intquery; scanf(%d,&query); if(query==1) { intdata; scanf(%d,&data); insert(start,data); } elseif(query==2) { intdata; scanf(%d,&data); delete(start,data); } elseif(query==3) { printf(Thelistis); print(start>next); printf(\n); } elseif(query==4) { intdata; scanf(%d,&data); intstatus=nd(start,data); if(status) { printf(ElementFound\n); } else { printf(ElementNotFound\n);} } }} 18.Canavariablebebothconstandvolatile?Yes.Theconstmodiermeansthatthiscodecannot changethevalueofthevariable,butthatdoesnotmeanthatthevaluecannotbechangedbymeans outsidethiscode.Forinstance,intheexampleinFAQ8,thetimerstructurewasaccessedthrougha volatileconstpointer.Thefunctionitselfdidnotchangethevalueofthetimer,soitwasdeclared const.However,thevaluewaschangedbyhardwareonthecomputer,soitwasdeclaredvolatile.Ifa variableisbothconstandvolatile,thetwomodierscanappearineitherorder. 19.whatareConstantandVolatileQualiers?

20 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

constisusedwithadatatypedeclarationordenitiontospecifyanunchangingvalue Examples: constintfive=5; constdoublepi=3.141593;

constobjectsmaynotbechanged Thefollowingareillegal: constintfive=5; constdoublepi=3.141593; pi=3.2; five=6;

volatilespeciesavariablewhosevaluemaybechangedbyprocessesoutsidethecurrent program Oneexampleofavolatileobjectmightbeabuerusedtoexchangedatawithanexternal device: int check_iobuf(void) { volatileintiobuf; intval; while(iobuf==0){ } val=iobuf; iobuf=0;

21 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

return(val); }

ifiobufhadnotbeendeclaredvolatile,thecompilerwouldnoticethatnothinghappensinside theloopandthuseliminatetheloop constandvolatilecanbeusedtogether Aninputonlybuerforanexternaldevicecouldbedeclaredasconst volatile(orvolatileconst,orderisnotimportant)tomakesurethecompilerknowsthat thevariableshouldnotbechanged(becauseitisinputonly)andthatitsvaluemaybealtered byprocessesotherthanthecurrentprogram Thekeywordsconstandvolatilecanbeappliedtoanydeclaration,includingthoseofstructures, unions,enumeratedtypesortypedefnames.Applyingthemtoadeclarationiscalledqualifyingthe declarationthatswhyconstandvolatilearecalledtypequaliers,ratherthantypespeciers.Here areafewrepresentativeexamples:

volatilei; volatileintj; constlongq; constvolatileunsignedlongintrt_clk; struct{ constlongintli; signedcharsc; }volatilevs;

Dontbeputo;someofthemaredeliberatelycomplicated:whattheymeanwillbeexplainedlater. Rememberthattheycouldalsobefurthercomplicatedbyintroducingstorageclassspecicationsas well!Infact,thetrulyspectacular

externconstvolatileunsignedlongintrt_clk;

isastrongpossibilityinsomerealtimeoperatingsystemkernels.

Letslookatwhatismeantwhenconstisused.Itsreallyquitesimple:constmeansthatsomething
22 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

isnotmodiable,soadataobjectthatisdeclaredwithconst asapartofitstypespecicationmust notbeassignedtoinanywayduringtherunofaprogram.Itisverylikelythatthedenitionofthe objectwillcontainaninitializer(otherwise,sinceyoucantassigntoit,howwoulditevergeta value?),butthisisnotalwaysthecase.Forexample,ifyouwereaccessingahardwareportataxed memoryaddressandpromisedonlytoreadfromit,thenitwouldbedeclaredtobeconstbutnot initialized. Takingtheaddressofadataobjectofatypewhichisntconstandputtingitintoapointerto theconstqualiedversionofthesametypeisbothsafeandexplicitlypermitted;youwillbeableto usethepointertoinspecttheobject,butnotmodifyit.Puttingtheaddressofaconsttypeintoa pointertotheunqualiedtypeismuchmoredangerousandconsequentlyprohibited(althoughyou cangetaroundthisbyusingacast).Hereisanexample:

#include<stdio.h> #include<stdlib.h> main(){ inti; constintci=123; /*declareapointertoaconst..*/ constint*cpi; /*ordinarypointertoanonconst*/ int*ncpi; cpi=&ci; ncpi=&i; /* *thisisallowed */ cpi=ncpi; /* *thisneedsacast *becauseitisusuallyabigmistake, *seewhatitpermitsbelow. */ ncpi=(int*)cpi; /* *nowtogetundefinedbehaviour... *modifyaconstthroughapointer */

23 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

*ncpi=0; exit(EXIT_SUCCESS); }

Example8.3 Astheexampleshows,itispossibletotaketheaddressofaconstantobject,generateapointertoa nonconstant,thenusethenewpointer.Thisisanerrorinyourprogramandresultsinundened behaviour. Themainintentionofintroducingconstobjectswastoallowthemtobeputintoreadonlystore,and topermitcompilerstodoextraconsistencycheckinginaprogram.Unlessyoudefeattheintentby doingnaughtythingswithpointers,acompilerisabletocheckthatconstobjectsarenotmodied explicitlybytheuser. Aninterestingextrafeaturepopsupnow.Whatdoesthismean?

charc; char*constcp=&c;

Itssimplereally;cpisapointertoachar,whichisexactlywhatitwouldbeiftheconstwerent there.Theconstmeansthatcpisnottobemodied,althoughwhateveritpointstocanbethe pointerisconstant,notthethingthatitpointsto.Theotherwayroundis

constchar*cp;

whichmeansthatnowcpisanordinary,modiablepointer,butthethingthatitpointstomustnot bemodied.So,dependingonwhatyouchoosetodo,boththepointerandthethingitpointstomay bemodiableornot;justchoosetheappropriatedeclaration.

Afterconst,wetreatvolatile.Thereasonforhavingthistypequalierismainlytodowiththe problemsthatareencounteredinrealtimeorembeddedsystemsprogrammingusingC.Imagine thatyouarewritingcodethatcontrolsahardwaredevicebyplacingappropriatevaluesinhardware registersatknownabsoluteaddresses.

24 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Letsimaginethatthedevicehastworegisters,each16bitslong,atascendingmemoryaddresses;the rstoneisthecontrolandstatusregister(csr)andthesecondisadataport.Thetraditionalwayof accessingsuchadeviceislikethis:

/*StandardCexamplebutwithoutconstorvolatile*/ /* *Declarethedeviceregisters *Whethertouseintorshort *isimplementationdependent */ structdevregs{ unsignedshortcsr;/*control&status*/ unsignedshortdata;/*dataport*/ }; /*bitpatternsinthecsr*/ #defineERROR0x1 #defineREADY0x2 #defineRESET0x4 /*absoluteaddressofthedevice*/ #defineDEVADDR((structdevregs*)0xffff0004) /*numberofsuchdevicesinsystem*/ #defineNDEVS4 /* *Busywaitfunctiontoreadabytefromdevicen. *checkrangeofdevicenumber. *WaituntilREADYorERROR *ifnoerror,readbyte,returnit *otherwisereseterror,return0xffff */ unsignedintread_dev(unsigneddevno){ structdevregs*dvp=DEVADDR+devno; if(devno>=NDEVS) return(0xffff); while((dvp>csr&(READY|ERROR))==0) ;/*NULLwaittilldone*/ if(dvp>csr&ERROR){

25 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

dvp>csr=RESET; return(0xffff); } return((dvp>data)&0xff); }

Example8.4 Thetechniqueofusingastructuredeclarationtodescribethedeviceregisterlayoutandnamesis verycommonpractice.Noticethattherearentactuallyanyobjectsofthattypedened,sothe declarationsimplyindicatesthestructurewithoutusingupanystore. Toaccessthedeviceregisters,anappropriatelycastconstantisusedasifitwerepointingtosucha structure,butofcourseitpointstomemoryaddressesinstead. However,amajorproblemwithpreviousCcompilerswouldbeinthewhileloopwhichteststhe statusregisterandwaitsfortheERRORorREADYbittocomeon.Anyselfrespectingoptimizing compilerwouldnoticethattheloopteststhesamememoryaddressoverandoveragain.Itwould almostcertainlyarrangetoreferencememoryonceonly,andcopythevalueintoahardwareregister, thusspeedinguptheloop.Thisis,ofcourse,exactlywhatwedontwant;thisisoneofthefewplaces wherewemustlookattheplacewherethepointerpoints,everytimearoundtheloop. Becauseofthisproblem,mostCcompilershavebeenunabletomakethatsortofoptimizationinthe past.Toremovetheproblem(andothersimilaronestodowithwhentowritetowhereapointer points),thekeywordvolatilewasintroduced.Ittellsthecompilerthattheobjectissubjectto suddenchangeforreasonswhichcannotbepredictedfromastudyoftheprogramitself,andforces everyreferencetosuchanobjecttobeagenuinereference. Hereishowyouwouldrewritetheexample,makinguseofconstandvolatiletogetwhatyou want.

/* *Declarethedeviceregisters *Whethertouseintorshort *isimplementationdependent */ structdevregs{ unsignedshortvolatilecsr; unsignedshortconstvolatiledata; }; /*bitpatternsinthecsr*/

26 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

#defineERROR0x1 #defineREADY0x2 #defineRESET0x4 /*absoluteaddressofthedevice*/ #defineDEVADDR((structdevregs*)0xffff0004) /*numberofsuchdevicesinsystem*/ #defineNDEVS4 /* *Busywaitfunctiontoreadabytefromdevicen. *checkrangeofdevicenumber. *WaituntilREADYorERROR *ifnoerror,readbyte,returnit *otherwisereseterror,return0xffff */ unsignedintread_dev(unsigneddevno){ structdevregs*constdvp=DEVADDR+devno; if(devno>=NDEVS) return(0xffff); while((dvp>csr&(READY|ERROR))==0) ;/*NULLwaittilldone*/ if(dvp>csr&ERROR){ dvp>csr=RESET; return(0xffff); } return((dvp>data)&0xff); }

Example8.5 Therulesaboutmixingvolatileandregulartypesresemblethoseforconst.Apointerto avolatileobjectcanbeassignedtheaddressofaregularobjectwithsafety,butitisdangerous(and needsacast)totaketheaddressofavolatileobjectandputitintoapointertoaregularobject. Usingsuchaderivedpointerresultsinundenedbehaviour. Ifanarray,unionorstructureisdeclaredwithconstorvolatileattributes,thenallofthemembers takeonthatattributetoo.Thismakessensewhenyouthinkaboutithowcouldamemberof aconststructurebemodiable?

27 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Thatmeansthatanalternativerewriteofthelastexamplewouldbepossible.Insteadofdeclaringthe deviceregisterstobevolatileinthestructure,thepointercouldhavebeendeclaredtopointto avolatilestructureinstead,likethis:

structdevregs{ unsignedshortcsr;/*control&status*/ unsignedshortdata;/*dataport*/ }; volatilestructdevregs*constdvp=DEVADDR+devno;

Sincedvppointstoavolatileobject,itnotpermittedtooptimizereferencesthroughthepointer. Ourfeelingisthat,althoughthiswouldwork,itisbadstyle.Thevolatiledeclarationbelongsinthe structure:itisthedeviceregisterswhicharevolatileandthatiswheretheinformationshouldbe kept;itreinforcesthefactforahumanreader. So,foranyobjectlikelytobesubjecttomodicationeitherbyhardwareorasynchronousinterrupt serviceroutines,thevolatiletypequalierisimportant. Now,justwhenyouthoughtthatyouunderstoodallthat,herecomesthenaltwist.Adeclaration likethis:

volatilestructdevregs{ /*stuff*/ }v_decl;

declaresthetypestructdevregsandalsoavolatilequaliedobjectofthattype,calledv_decl. Alaterdeclarationlikethis

structdevregsnv_decl;

declaresnv_declwhichisnotqualiedwithvolatile!Thequalicationisnotpartofthetype ofstructdevregsbutappliesonlytothedeclarationofv_decl.Lookatitthiswayround,which perhapsmakesthesituationmoreclear(thetwodeclarationsarethesameintheireect):

structdevregs{ /*stuff*/ }volatilev_decl;

28 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Ifyoudowanttogetashorthandwayofattachingaqualiertoanothertype,youcan usetypedeftodoit:

structx{ inta; }; typedefconststructxcsx; csxconst_sx; structxnon_const_sx={1}; const_sx=non_const_sx;/*errorattempttomodifyaconst*/

20.WhatarethedierencesbetweenaunionandastructureinC? Aunionisawayofprovidinganalternatewayofdescribingthesamememoryarea.Inthisway,you couldhaveastructthatcontainsaunion,sothatthestatic,orsimilarportionofthedatais describedrst,andtheportionthatchangesisdescribedbytheunion.Theideaofaunioncouldbe handledinadierentwaybyhaving2dierentstructsdened,andmakingapointertoeachkindof struct.Thepointertostructacouldbeassignedtothevalueofabuer,andthepointertostruct bcouldbeassignedtothesamebuer,butnowa>someeldandb>someothereldareboth locatedinthesamebuer.Thatistheideabehindaunion.Itgivesdierentwaystobreakdownthe samebuerarea. Thedierencebetweenstructureandunionare:1.unionallocatesthememoryequaltothe maximummemoryrequiredbythememberoftheunionbutstructureallocatesthememoryequalto thetotalmemoryrequiredbythemembers.2.Inunion,oneblockisusedbyallthememberofthe unionbutincaseofstructure,eachmemberhavetheirownmemoryspace DierenceBetweenStuctureandUnion: Structure i.AccessMembers Wecanaccessallthemembersofstructureat anytime. ii.MemoryAllocation Memoryisallocatedforallvariables. iii.Initialization Allmembersofstructurecanbeinitialized iv.Keyword Onlytherstmemberofaunioncanbe initialized. Allocatesmemoryforvariablewhichvariable requiremorememory. Onlyonememberofunioncanbeaccessedat anytime. Union

29 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

structkeywordisusedtodeclarestructure. v.Syntax structstruct_name { structureelement1; structureelement2; structureelementn; }struct_var_nm;

unionkeywordisusedtodeclareunion.

unionunion_name { unionelement1; unionelement2; unionelementn; }union_var_nm;

vi.Example structitem_mst { intrno; charnm[50]; }it; unionitem_mst { intrno; charnm[50]; }it;

Whilestructureenablesustreatanumberofdierentvariablesstoredatdierentinmemory,a unionenablesustotreatthesamespaceinmemoryasanumberofdierentvariables.Thatisa Unionoersawayforasectionofmemorytobetreatedasavariableofonetypeononeoccasion andasadierentvariableofadierenttypeonanotheroccasion. Thereisfrequentrequirementwhileinteractingwithhardwaretoaccessaccessabyteorgroupof bytessimultaneouslyandsometimeseachbyteindividually.Usuallyunionistheanswer. =======DierenceWithexample======= Letssayastructurecontaininganint,charandoatiscreatedandaunioncontainingintcharoat aredeclared. structTT{inta;oatb;charc;}UnionUU{inta;oatb;charc;} sizeofTT(struct)wouldbe>9bytes(compilerdependentifint,oat,chararetakenas4,4,1) sizeofUU(Union)wouldbe4bytesassupposedfromabove.Ifavariableindoubleexistsinunion thenthesizeofunionandstructwouldbe8bytesandcumulativesizeofallvariablesinstruct.

30 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

structfoo { charc; longl; char*p; }; unionbar { charc; longl; char*p; }; Astructfoocontainsalloftheelementsc,l,andp.Eachelementisseparateanddistinct. Aunionbarcontainsonlyoneoftheelementsc,l,andpatanygiventime.Eachelementisstoredin thesamememorylocation(well,theyall startatthesamememorylocation),andyoucanonlyrefertotheelementwhichwaslaststored.(ie: afterbarptr>c=2;youcannotreference anyoftheotherelements,suchasbarptr>pwithoutinvokingundenedbehavior.) Trythefollowingprogram.(Yes,Iknowitinvokestheabovementionedundenedbehavior,but mostlikelywillgivesomesortofoutputonmostcomputers.) ========== #include structfoo { charc; longl; char*p; }; unionbar { charc; longl; char*p; }; intmain(intargc,char*argv[])

31 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

{ structfoomyfoo; unionbarmybar; myfoo.c=1; myfoo.l=2L; myfoo.p=Thisismyfoo; mybar.c=1; mybar.l=2L; mybar.p=Thisismybar; printf(myfoo:%d%ld%s\n,myfoo.c,myfoo.l,myfoo.p); printf(mybar:%d%ld%s\n,mybar.c,mybar.l,mybar.p); return0; } ========== Onmysystem,Iget: myfoo:12Thisismyfoo mybar:1004197476Thisismybar ========== credittooriginalauthor. Structure:Structureisacombinationelements,whichcanbepredeneddatatypesorotherstructure. Thelength/sizeofthestructureisthesumofthelengthofitselements. InC,structurescannotcontainfunctions.inC++itcan. Union:Unionisacombinationelements,whichcanbepredeneddatatypesorotherunion.But,the size/lengthofunionisthemaximumofinternalelements. thesizeof()operatorreturnsthesizeslightlymorethancalculatedsizeduetopadding,whichagain dependsonOS ==Answer==Unionallocatesthememoryequaltothemaximummemoryrequiredbythemember oftheunionbutstructureallocatesthememoryequaltothetotalmemoryrequiredbythemembers. Inunion,oneblockisusedbyallthememberoftheunionbutincaseofstructure,eachmemberhave theirownmemoryspace. 21.Whatismeantbystructurepadding? Answer:compilerspadstructurestooptimizedatatransfers.Thisisanhardwarearchitectureissue. MostmodernCPUsperformbestwhenfundamentaltypes,likeintoroat,arealignedonmemory boundariesofaparticularsize(eg.oftena4bytewordon32bitarchs).Manyarchitecturesdontallow misalignedaccessoriftheydoinoccuraperformancepenality.Whenacompilerprocessesa structuredeclarationitwilladdextrabytesbetweeneldstomeetalignmentneeds. Mostprocessorsrequirespecicmemoryalignmentonvariablescertaintypes.Normallythe

32 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

minimumalignmentisthesizeofthebasictypeinquestion,forinstancethisiscommon charvariablescanbebytealignedandappearatanybyteboundary short(2byte)variablesmustbe2bytealigned,theycanappearatanyevenbyteboundary.This meansthat010004567isnotavalidlocationforashortvariablebut010004566is. long(4byte)variablesmustbe4bytealigned,theycanonlyappearatbyteboundariesthatarea multipleof4bytes.Thismeansthat010004566isnotavalidlocationforalongvariablebut 010004568is. Structurepaddingoccursbecausethemembersofthestructuremustappearatthecorrectbyte boundary,toachievethisthecompilerputsinpaddingbytes(orbitsifbiteldsareinuse)sothatthe structuremembersappearinthecorrectlocation.Additionallythesizeofthestructuremustbesuch thatinanarrayofthestructuresallthestructuresarecorrectlyalignedinmemorysotheremaybe paddingbytesattheendofthestructuretoo structexample{ charc1; shorts1; charc2; longl1; charc3; } Inthisstructure,assumingthealignmentschemeIhavepreviouslystatedthen c1canappearatanybyteboundary,howevers1mustappearata2byteboundarysothereisa paddingbytebetweenc1ands1. c2canthenappearintheavailablememorylocation,howeverl1mustbeata4byteboundaryso thereare3paddingbytesbetweenc2andl1 c3thenappearintheavailablememorylocation,howeverbecausethestructurecontainsalong memberthestructuremustbe4bytealignedandmustbeamultipleof4bytesinsize.Therefore thereare3paddingbytesattheendofthestructure.Itwouldappearinmemoryinthisorder c1 paddingbyte s1byte1 s1byte2 c2 paddingbyte paddingbyte paddingbyte l1byte1 l1byte2 l1byte3 l1byte4 c3
33 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

paddingbyte paddingbyte paddingbyte Thestructurewouldbe16byteslong. rewrittenlikethis structexample{ longl1; shorts1; charc1; charc2; charc3; } Thenl1appearsatthecorrectbytealignment,s1willbecorrectlyalignedsononeedforpadding betweenl1ands1.c1,c2,c3canappearatanylocation.Thestructuremustbeamultipleof4bytesin sizesinceitcontainsalongso3paddingbytesappearafterc3 Itappearsinmemoryintheorder l1byte1 l1byte2 l1byte3 l1byte4 s1byte1 s1byte2 c1 c2 c3 paddingbyte paddingbyte paddingbyte andisonly12byteslong. Ishouldpointoutthatstructurepackingisplatformandcompiler(andinsomecasescompiler switch)dependent. MemoryPoolsarejustasectionofmemoryreservedforallocatingtemporarilytootherpartsofthe application Amemoryleakoccurswhenyouallocatesomememoryfromtheheap(orapool)andthendeleteall referencestothatmemorywithoutreturningittothepoolitwasallocatedfrom. Program: structMyStructA{ chara;

34 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

charb; intc; }; structMyStructB{ chara; intc; charb; }; intmain(void){ intsizeA=sizeof(structMyStructA); intsizeB=sizeof(structMyStructB); printf(A=%d\n,sizeA); printf(B=%d\n,sizeB); return0; } 22.WhatisthedierencebetweenmacroandconstantvariablesinC? Macrosarereplacedbypreprocessor,butinconstantdatatypewillbecheckedbycompiler.Macros arereplacedwithoutcheckingthevaluessometimestheprogrammerwanttochangevaluesonlyina singlefunctionatthatprefertouseconstantthanamacro. ThersttechniquecomesfromtheCprogramminglanguage.Constantsmaybedenedusingthe preprocessordirective,#deneThepreprocessorisaprogramthatmodiesyoursourcelepriorto compilation.Commonpreprocessordirectivesare#include,whichisusedto includeadditionalcodeintoyoursourcele,#dene,whichisusedtodeneaconstantand #if/#endif,whichcanbeusedtoconditionallydeterminewhichpartsofyourcodewillbecompiled. The#denedirectiveisusedasfollows. #denepi3.1415#deneid_no12345 Wherevertheconstantappearsinyoursourcele,thepreprocessorreplacesitbyitsvalue.So,for instance,everypiinyoursourcecodewillbereplaceby3.1415.Thecompilerwillonlyseethe value3.1415inyourcode,notpi.Theproblemwiththistechniqueisthatthereplacementisdone lexically,withoutanytypechecking,withoutanyboundcheckingandwithoutanyscopechecking. Everypiisjustreplacedbyitsvalue.Thetechniqueisoutdated,existstosupportlegacycodeand shouldbeavoided. Const Thesecondtechniqueistousethekeywordconstwhendeningavariable.Whenusedthecompiler willcatchattemptstomodifyvariablesthathavebeendeclaredconst. constoatpi=3.1415;constintid_no=12345;

35 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Therearetwomainadvantagesoverthersttechnique. First,thetypeoftheconstantisdened.piisoat.id_noisint.Thisallowssometypechecking bythecompiler.&nbsp; Second,theseconstantsarevariableswithadenitescope.Thescopeofavariablerelatestopartsof yourprograminwhichitisdened.Somevariablesmayexistonlyincertainfunctionsorincertain blocksofcode. Ex:Youmaywanttouseid_noinonefunction andacompletelyunrelatedid_noinyourmainprogram. 23.WhatisdierencebetweenreentrantfunctionandrecursivefunctioninC? Answer:Reentrantfunctionisafunctionwhichguaranteedthatwhichcanbeworkwellundermulti threadedenvironment.meanwhilefunctionisaccessbyonethread,anotherthreadcancallitmean thereisseparateexecutionstackandhandlingforeach.Sofunctionshouldnotcontainanystaticor sharedvariablewhichcanharmordisturbtheexecution.Meanfunctionwhichcanbecalledby thread,whilerunningfromanotherthreadsafelyandproperly Example:

intt; voidswap(int*x,int*y) { ints; s=t;//saveglobalvariable t=*x; *x=*y; //hardwareinterruptmightinvokeisr()here! *y=t; t=s;//restoreglobalvariable } voidisr() { intx=1,y=2; swap(&x,&y); }

RecursivefunctionExample: voiddoll(intsize) { if(size==0)//Nodollcanbesmallerthan1atom(10^0==1)sodoesntcallitself

36 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

return;//Returndoesnothavetoreturnsomething,itcanbeused //toexitafunction doll(size1);//Decrementsthesizevariablesothenextdollwillbesmaller. } intmain() { doll(10);//Startsowithalargedoll(itsalogarithmicscale) 24.WhatisVModel?Whatarethebenets? TheVmodelrepresentsasoftwaredevelopmentprocess(alsoapplicabletohardwaredevelopment) whichmaybeconsideredanextensionofthewaterfallmodel.Insteadofmovingdowninalinear way,theprocessstepsarebentupwardsafterthecodingphase,toformthetypicalVshape.The VModeldemonstratestherelationshipsbetweeneachphaseofthedevelopmentlifecycleandits associatedphaseoftesting. TheVmodelhasanumberofbenets: 1.Systemsdevelopmentprojectsusuallyhaveatestapproach,orteststrategydocument,which deneshowtestingwillbeperformedthroughoutthelifecycleoftheproject.TheVmodelprovidesa consistentbasisandstandardforpartofthatstrategy. 2.TheVmodelexplicitlysuggeststhattesting(qualityassurance)shouldbeconsideredearlyonin thelifeofaproject.Testingandxingcanbedoneatanystageinthelifecycle.However,thecostof ndingandxingfaultsincreasesdramaticallyasdevelopmentprogresses.Evidencesuggeststhatif afaultuncoveredduringdesigncosts1.0monetaryunittocorrect,thenthesamefaultuncoveredjust beforetestingwillcost6.5units,duringtesting15units,andafterreleasebetween60and100units. Theneedtondfaultsassoonaspossiblereinforcestheneedforthequalityassuranceofdocuments suchastherequirementsspecicationandthefunctionalspecication.Thisisperformedusingstatic testingtechniquessuchasinspectionsandwalkthroughs. 3.Itintroducestheideaofspecifyingtestrequirementsandexpectedoutcomespriortoperforming theactualtests.Forexample,theacceptancetestsareperformedagainstaspecicationof requirements,ratherthanagainstsomecriteriadreamedupwhentheacceptancestagehasbeen reached 4.TheVmodelprovidesafocusfordeningthetestingthatmusttakeplacewithineachstage.The denitionoftestingisassistedbytheideaofentryandexitcriteria.Hence,themodelcanbeusedto denethestateadeliverablemustbeinbeforeitcanenterandleaveeachstage.Theexitcriteriaof onestageareusuallytheentrycriteriaofthenext.Inmanyorganizations,thereisconcernaboutthe qualityoftheprogramcodereleasedbyindividualprogrammers.Someprogrammersreleasecode thatappearstobefaultfree,whileothersreleasecodethatstillhasmanyfaultsinit.Theproblemof programmersreleasingcodewithdierentlevelsofrobustnesswouldbeaddressedintheexit criteriaofunitdesignandunittesting.Unitdesignwouldrequireprogrammerstospecifytheir intendedtestcasesbeforetheywroteanyprogramcode.Codingcouldnotbeginuntilthesetestcases hadbeenagreedwithanappropriatemanager.Second,thetestcaseswouldhavetobeconducted successfullybeforetheprogramcouldleavetheunitteststageandbereleasedtointegrationtesting. 5.Finally,theVmodelprovidesabasisfordeningwhoisresponsibleforperformingthetestingat

37 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

eachstage.Herearesometypicalresponsibilities: acceptancetestingperformedbyusers systemtestingperformedbysystemtesters integrationtestingperformedbyprogramteamleaders unittestingperformedbyprogrammers. TheVmodelisthereforeanexcellentbasisforthepartitioningoftesting,highlightingthefactthatall theparticipantsinthedevelopmentofasystemhavearesponsibilityforqualityassuranceand testing. 25.WhatismeantbyBlackboxtestingandwhiteboxtesting? Whiteboxtesting(alsoknownasclearboxtesting,glassboxtesting,transparentboxtesting, andstructuraltesting)isamethodoftestingsoftwarethattestsinternalstructuresorworkingsofan application,asopposedtoitsfunctionality(i.e.blackboxtesting).Inwhiteboxtestinganinternal perspectiveofthesystem,aswellasprogrammingskills,areusedtodesigntestcases.Thetester choosesinputstoexercisepathsthroughthecodeanddeterminetheappropriateoutputs.Thisis analogoustotestingnodesinacircuit,e.g.incircuittesting(ICT). Whilewhiteboxtestingcanbeappliedattheunit,integrationandsystemlevelsofthesoftware testingprocess,itisusuallydoneattheunitlevel.Itcantestpathswithinaunit,pathsbetweenunits duringintegration,andbetweensubsystemsduringasystemleveltest.Thoughthismethodoftest designcanuncovermanyerrorsorproblems,itmightnotdetectunimplementedpartsofthe specicationormissingrequirement. Blackboxtestingisamethodofsoftwaretestingthatteststhefunctionalityofanapplicationas opposedtoitsinternalstructuresorworkings(seewhiteboxtesting).Thismethodoftestcanbe appliedtoalllevelsofsoftwaretesting:unit,integration,systemandacceptance.Ittypically comprisesmostifnotalltestingathigherlevels,butcanalsodominateunittestingaswell. (http://en.wikipedia.org/wiki/File:Blackbox.svg) WhiteBoxTesting:Meanstestingtheapplicationwithcoding/programmingknowledge.That meansthetesterhastocorrectthecodealso. Blackboxtesting:Testingtheapplicationwithoutcoding/programmingknowledgethatmeansthe testerdoesntrequirecodingknowledge.Justheexaminestheapplicationexternalfunctional behaviourandGUIfeatures. Sl.No 1 2 BlackBox Focusesonthefunctionalityofthe system Techniquesusedare: Equivalencepartitioning Boundaryvalueanalysis Errorguessing WhiteBox Focusesonthestructure(Program)of thesystem Techniquesusedare: BasisPathTesting FlowGraphNotation ControlStructureTesting

38 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Raceconditions Causeeectgraphing Syntaxtesting Statetransitiontesting Graphmatrix

1.ConditionTesting 2.DataFlowtesting LoopTesting 1.SimpleLoops 2.NestedLoops 3.ConcatenatedLoops 4.UnstructuredLoops

3 4

Testercanbenontechnical

Testershouldbetechnical Helpstoidentifythelogicaland codingissues.

Helpstoidentifythevaguenessand contradictioninfunctional specications 26.Whatarethetypesoftestings? unittesting Componenttesting Integrationtesting Systemtesting

27.TheDierencebetweenBitRateandBaudRate? ThedierencebetweenBitandBaudrateiscomplicatedandintertwining.Botharedependentand interrelated.ButthesimplestexplanationisthataBitRateishowmanydatabitsaretransmittedper second.AbaudRateisthenumberoftimespersecondasignalinacommunicationschannel changes. Bitratesmeasurethenumberofdatabits(thatis0sand1s)transmittedinonesecondina communicationchannel.Agureof2400bitspersecondmeans2400zerosoronescanbetransmitted inonesecond,hencetheabbreviationbps.Individualcharacters(forexamplelettersornumbers) thatarealsoreferredtoasbytesarecomposedofseveralbits. Abaudrateisthenumberoftimesasignalinacommunicationschannelchangesstateorvaries.For example,a2400baudratemeansthatthechannelcanchangestatesupto2400timespersecond.The termchangestatemeansthatitcanchangefrom0to1orfrom1to0uptoX(inthiscase,2400) timespersecond.Italsoreferstotheactualstateoftheconnection,suchasvoltage,frequency,or phaselevel). Themaindierencebetweenthetwoisthatonechangeofstatecantransmitonebit,orslightlymore orlessthanonebit,thatdependsonthemodulationtechniqueused.Sothebitrate(bps)andbaud rate(baudpersecond)havethisconnection:

39 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

bps=baudpersecondxthenumberofbitperbaud Themodulationtechniquedeterminesthenumberofbitperbaud.Herearetwoexamples: WhenFSK(FrequencyShiftKeying,atransmissiontechnique)isused,eachbaudtransmitsonebit. Onlyonechangeinstateisrequiredtosendabit.Thus,themodemsbpsrateisequaltothebaud rate.Whenabaudrateof2400isused,amodulationtechniquecalledphasemodulationthat transmitsfourbitsperbaudisused.So: 2400baudx4bitsperbaud=9600bps Suchmodemsarecapableof9600bpsoperation. 3)DierencebetweenashandEEprom 1. Similarities BothashandEEPROMaredigitalstoragemethodsusedbycomputersandotherdevices.Both arenonvolatileROMtechnologiestowhichyoucanwriteandfromwhichyoucanerasemultiple times. Dierences TheprimarydierencebetweenashandEEPROMisthewaytheyerasedata.WhileEEPROM destroystheindividualbytesofmemoryusedtostoredata,ashdevicescanonlyerasememory inlargerblocks.Thismakesashdevicesfasteratrewriting,astheycanaectlargeportionsof memoryatonce.Sincearewritemayaectunusedblocksofdata,italsoaddsunnecessarilyto usageofthedevice,shorteningitslifespanincomparisonwithEEPROM. Usage FlashstorageiscommonlyusedinUSBmemorydrivesandsolidstateharddrives.EEPROMis usedinavarietyofdevices,fromprogrammableVCRstoCDplayers. 28.Canstructuresbepassedtothefunctionsbyvalue? Ans:yesstructurescanbepassedbyvalue.Butunnecessarymemorywastage. 29.Whycannotarraysbepassedbyvaluestofunctions? Ans:Whenaarrayispassedtoafunction,thearrayisinternallychangedtoapointer.Andpointers arealwayspassedbyreference. 30.Whatismeantbystaticfunctions? Ans:staticfunctionsarefunctionsthatareonlyvisibletootherfunctionsinthesamele Example: main.c #include<STDIO.H>

40 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

main() { Func1(); Func2(); }

funcs.c /************************************* * *Functiondeclarations(prototypes). * *************************************/ /*Func1isonlyvisabletofunctionsinthisfile.*/ staticvoidFunc1(void); /*Func2isvisabletoallfunctions.*/ voidFunc2(void); /************************************* * *Functiondefinitions * *************************************/ voidFunc1(void) { puts("Func1called"); } /*************************************/voidFunc2(void) { puts("Func2called"); }

31.Dierencebetweendeclaration,denition&initialization? Ans:Adeclarationintroducesanameanidentiertothecompiler.IttellsthecompilerThis functionorthisvariableexistssomewhere,andhereiswhatitshouldlooklike.


41 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Adenition,ontheotherhand,says:MakethisvariablehereorMakethisfunction here.It allocatesstorageforthename.Thismeaningworkswhether youretalkingaboutavariableorafunction;ineithercase,atthepointofdenitionthecompiler allocatesstorage. externconstintx=1;/*Initialization*/ Thisinitializationestablishesthisasadenition,notadeclaration. externconstintx;/*Declaration*/ ThisdeclarationinC++meansthatthedenitionexistselsewhere. 32.Whatisthedierencebetweenpassbyvaluebyreferenceincandpassbyreferenceinc? PassByReference: InPassbyreferenceaddressofthevariableispassedtoafunction.Whateverchangesmadetotheformal parameterwillaecttotheactualparameters Samememorylocationisusedforbothvariables.(FormalandActual) itisusefulwhenyourequiredtoreturnmorethen1values PassByValue: Inthismethodvalueofthevariableispassed.Changesmadetoformalwillnotaecttheactualparameters. Dierentmemorylocationswillbecreatedforbothvariables. Heretherewillbetemporaryvariablecreatedinthefunctionstackwhichdoesnotaecttheoriginalvariable. 33.Whatisthedierencebetweenashmemory,EPROMandEEPROM? EEPROMisanolder,morereliabletechnology.ItissomewhatslowerthanFlash.FlashandEEPROM areverysimilar,butthereisasubtledierence.FlashandEEPROMbothusequantumcellstotrap electons.Eachcellrepresentsonebitofdata.Thepresenceorabsenceofelectonsinacellindicates whetherthebitisa1or0.Thecellshaveanitelifeeverytimeacelliserased,itwearsoutalittle bit.InEEPROM,cellsareerasedonebyone.Theonlycellserasedarethosewhichare1butneedto bezero.(Writinga1toacellthats0causesverylittlewear,IIRC)InFlash,alargeblockiserasedall atonce.Insomedevices,thisblockistheentiredevice.Soinash,cellsareerasedwhetherthey needitornot.Thiscutsdownonthelifespanofthedevice,butismuch,muchfasterthanthe EEPROMmethodofgoingcellbycell. Erasuremethod:BothFlashandEEPROMerasecellsbymeansofanelectriceld.Ithinkitis highfrequencyandpopstheelectronsoutoftheOthersimilardevicesareEPROM(sometimes UVEPROM)andOTPROM(sometimesPROM).EPROM/UVEPROMlacksthestructuresthat generatetheelectricaleldforerasure.Thesedeviceshaveawindowontop,usuallycoveredbya papersticker.Toerase,thestickerisremovedandthedeviceisexposedtointenseultravioletlightfor 3045minutes.TheonlydierencebetweenOTPROMandUVEPROMisthatOTPROMlackstheUV windowthereisnowaytoerasethedata.AddingtheUVwindowtothedevicepackage signicantlyincreasescost,sothereisanicheforonetimeprogrammabledevices

TheinformationstoredinanEPROMchipcanbeerasedbyexposingthechiptostrongUVlight.

42 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

EPROMchipsareeasilyrecognizedbythesmallquartz windowusedforerasure.Onceerasedthe chipcanbereprogrammed. EPROMismoreexpensivetobuyperunitcost,butcanprovecheaperinthelongrunforsome applications.ForexampleifPROMwasusedforrmwarethatneededupgradedevery6monthsor soitcouldprovequiteexpensivebuyingnewchips!

Thishastheaddedadvantagethattheinformationstoredcanberewritteninblocksandhencecan beusedtostoresystemsettingsthattheusermaywanttochangeperiodically. Thissolidstatememoryhasconsiderablyreducedinpriceoverrecentyearsandisnowadays commonlyusedtostoresystemsettingssuchasBIOSsettings 34.WhatisdierencebetweenVolatile&NonVolatileMemory? Volatilememory Volatilememoryiscomputermemorythatrequirespowertomaintainthestoredinformation.Most modernsemiconductorvolatilememoryiseitherStaticRAM(seeSRAM)ordynamicRAM(see DRAM).SRAMretainsitscontentsaslongasthepowerisconnectedandiseasytointerfacetobut usessixtransistorsperbit.DynamicRAMismorecomplicatedtointerfacetoandcontrolandneeds regularrefreshcyclestopreventitscontentsbeinglost.However,DRAMusesonlyonetransistorand acapacitorperbit,allowingittoreachmuchhigherdensitiesand,withmorebitsonamemorychip, bemuchcheaperperbit.SRAMisnotworthwhilefordesktopsystemmemory,whereDRAM dominates,butisusedfortheircachememories.SRAMiscommonplaceinsmallembeddedsystems, whichmightonlyneedtensofkilobytesorless.Forthcomingvolatilememorytechnologiesthathope toreplaceorcompetewithSRAMandDRAMincludeZRAM,TTRAM,ARAMandETARAM.

Nonvolatilememoryiscomputermemorythatcanretainthestoredinformationevenwhennot powered.Examplesofnonvolatilememoryincludereadonlymemory(seeROM),ashmemory, mosttypesofmagneticcomputerstoragedevices(e.g.harddisks,oppydiscsandmagnetictape), opticaldiscs,andearlycomputerstoragemethodssuchaspapertapeandpunchedcards. ForthcomingnonvolatilememorytechnologiesincludeFeRAM,CBRAM,PRAM,SONOS,RRAM, Racetrackmemory,NRAMandMillipede.

43 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

35.Whatisareentrantfunction? Areentrantfunctionisafunctionwhichcanbesafelyexecutedconcurrently.Thismeansitshould allowareentrywhileitisrunning.Thereentrantfunctionshouldworkonlyonthedatagivenbythe callingfunction.Itmustnothaveanystaticdataalso. Thetermreentrantisusedtorefertosidewallprolesofthenozzles,whereinexitdiametersofthe nozzlesaresmallerthanentrancediametersofthenozzlessothatthesidewallsofthenozzlesarenot perpendiculartoaplanedenedbyanexitsurfaceofthenozzlemember. AReentrantfunctionisafunctionwhichguaranteedthatwhichcanbeworkwellundermulti threadedenvironment.Meanwhilefunctionisaccessbyonethread,anotherthreadcancallit meanthereisseparateexecutionstackandhandlingforeach.Sofunctionshouldnotcontainany staticorsharedvariablewhichcanharmordisturbtheexecution. 36.WhyweareusingUDS,IfCANsupportdiagnosticscommunication? InCANitwillsupportinternaldiagnosticmessages.UDS&KWP2000areusedfortotestwith externaltesterandtoknowthetypeofproblem 37.HowtorecoverfromCANBuso?

TodistinguishbetweentemporaryandpermanentfailureseveryCANbuscontrollerhastwoError Counters:TheREC(ReceiveErrorCounter)andtheTEC(TransmitErrorCounter).Thecountersare incrementedupondetectederrorsrespectivelyaredecrementeduponcorrecttransmissionsor receptions.Dependingonthecountervaluesthestateofthenodeischanged:Theinitialstateofa CANbuscontrollerisErrorActivethatmeansthecontrollercansendactiveErrorFlags.The controllergetsintheErrorPassivestateifthereisanaccumulationoferrors. OnCANbuscontrollerfailureoranextremeaccumulationoferrorsthereisastatetransitiontoBus O.Thecontrollerisdisconnectedfromthebusbysettingitinastateofhighresistance.TheBusO stateshouldonlybeleftbyasoftwarereset.AftersoftwareresettheCANbuscontrollerhasto waitfor128x11recessivebitstotransmitaframe.Thisisbecauseothernodesmaypending transmissionrequests.Itisrecommendednottostartanhardwareresetbecausethewaittimerule willnotbefollowedthen.

44 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

37.WhatisVirtualfunctionalbus? Virtualfunctionbuscanbedescribedasasystemmodelingandcommunicationconcept.Itislogical entitythatfacilitatesthe conceptofrelocatabilitywithintheAUTOSARsoftwarearchitecturebyprovidingavirtual infrastructurethatisindependentfromanyactualunderlyinginfrastructureandprovidesallservices requiredforavirtualinteractionbetweenAUTOSARcomponents. 38.IntraandInterECUcommunication? IntraECUwhichdenotesthecommunicationbetweentwosoftwarecomponentsresidingonthe sameECUandInterECUwhichdenotesthesituationwhentwosoftwarecomponentsresideon dierentECUsthatareconnectedviaabusnetwork. 39.Whatisthedierencebetweenglobalandstaticglobalvariables? Globalvariablesarevariablesdenedoutsideofanyfunction.Theirscopestartsatthepointwhere theyaredenedandlaststotheendofthele.Theyhaveexternallinkage,whichmeansthatinother sourceles,thesamenamereferstothesamelocationinmemory. Staticglobalvariablesareprivatetothesourcelewheretheyaredenedanddonotconictwith othervariablesinothersourceleswhichwouldhavethesamename. 40.HowtoaccessaGlobalvariablesinotherles? Variablesdeclaredoutsideofablockarecalledglobalvariables.Globalvariableshaveprogram scope,whichmeanstheycanbeaccessedeverywhereintheprogram,andtheyareonlydestroyed whentheprogramends. Hereisanexampleofdeclaringaglobalvariable: 1 2 3 4 5 6 7 8 9 10 intg_nX;//globalvariable intmain() { intnY;//localvariablenY //globalvarscanbeseeneverywhereinprogram //sowecanchangetheirvalueshere g_nX=5; }//nYisdestroyedhere Becauseglobalvariableshaveprogramscope,theycanbeusedacrossmultipleles.Inthesectionon programswithmultipleles,youlearnedthatinordertouseafunctiondeclaredinanotherle,you havetouseaforwarddeclaration,oraheaderle. Similarly,inordertouseaglobalvariablethathasbeendeclaredinanotherle,youhavetousea forwarddeclarationoraheaderle,alongwiththeexternkeyword.Externtellsthecompilerthat youarenotdeclaringanewvariable,butinsteadreferringtoavariabledeclaredelsewhere.

45 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Hereisanexampleofusingaforwarddeclarationstyleextern: global.cpp: 1 2 //declarationofg_nValue intg_nValue=5;

main.cpp: 1 2 3 4 5 6 7 8 //externtellsthecompilerthisvariableisdeclaredelsewhere externintg_nValue; intmain() { g_nValue=7; return0; } Hereisanexampleofusingaheaderleextern: global.cpp: 1 2 //declarationofg_nValue intg_nValue=5;

global.h: 1 2 3 4 5 6 7 #ifndefGLOBAL_H//headerguards #defineGLOBAL_H //externtellsthecompilerthisvariableisdeclaredelsewhere externintg_nValue; #endif main.cpp: 1 2 3 4 5 6 #include"global.h" intmain() { g_nValue=7; return0; }

Generallyspeaking,ifaglobalvariableisgoingtobeusedinmorethan2les,itsbettertousethe headerleapproach.Someprogrammersplaceallofaprogramsglobalvariablesinalecalled globals.cpp,andcreateaheaderlenamedglobals.htobeincludedbyother.cpplesthatneedto usethem.


46 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Localvariableswiththesamenameasaglobalvariablehidetheglobalvariableinsidethatblock. However,theglobalscopeoperator(::)canbeusedtotellthecompileryoumeantheglobalversion: 1 2 3 4 5 6 7 8 9 intnValue=5; intmain() { intnValue=7;//hidestheglobalnValuevariable nValue++;//incrementslocalnValue,notglobalnValue ::nValue;//decrementsglobalnValue,notlocalnValue return0; }//localnValueisdestroyed However,havinglocalvariableswiththesamenameasglobalvariablesisusuallyarecipefor trouble,andshouldbeavoidedwheneverpossible.UsingHungarianNotation,itiscommonto declareglobalvariableswithag_prex.Thisisaneasywaytodierentiateglobalvariablefrom localvariables,andavoidvariablesbeinghiddenduetonamingcollisions. Newprogrammersareoftentemptedtouselotsofglobalvariables,becausetheyareeasytowork with,especiallywhenmanyfunctionsareinvolved.However,thisisaverybadidea.Infact,global variablesshouldgenerallybeavoidedcompletely! Whyglobalvariablesareevil Globalvariablesshouldbeavoidedforseveralreasons,buttheprimaryreasonisbecausethey increaseyourprogramscomplexityimmensely.Forexample,sayyouwereexaminingaprogram andyouwantedtoknowwhatavariablenamedg_nValuewasusedfor.Becauseg_nValueisa global,andglobalscanbeusedanywhereintheentireprogram,youdhavetoexamineeverysingle lineofeverysinglele!Inacomputerprogramwithhundredsoflesandmillionsoflinesofcode, youcanimaginehowlongthiswouldtake! Second,globalvariablesaredangerousbecausetheirvaluescanbechangedbyanyfunctionthatis called,andthereisnoeasywayfortheprogrammertoknowthatthiswillhappen.Considerthe followingprogram: 1 2 3 4 5 6 7 8 9 10 11 12 //declareglobalvariable intg_nMode=1; voiddoSomething() { g_nMode=2; } intmain() {

47 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

13 14 15 16 17 18 19 20 21 22 23 24

g_nMode=1; doSomething(); //Programmerexpectsg_nModetobe1 //ButdoSomethingchangeditto2! if(g_nMode==1) cout<<"Nothreatdetected."<<endl; else cout<<"Launchingnuclearmissiles..."<<endl; return0;

} Notethattheprogrammersetg_nModeto1,andthencalleddoSomething().Unlesstheprogrammer hadexplicitknowledgethatdoSomething()wasgoingtochangethevalueofg_nMode,heorshewas probablynotexpectingdoSomething()tochangethevalue!Consequently,therestofmain()doesnt workliketheprogrammerexpects(andtheworldisobliterated). Globalvariablesmakeeveryfunctioncallpotentiallydangerous,andtheprogrammerhasnoeasy wayofknowingwhichonesaredangerousandwhichonesarent!Localvariablesaremuchsafer becauseotherfunctionscannotaectthemdirectly.Consequently,globalvariablesshouldnotbe usedunlessthereisaverygoodreason! 41.WhatistheuseofComplexDeviceDriversinAUTOSAR? SincetheAUTOSARlayeredsoftwarearchitecturerestrictsdirectaccesstohardwarefromupper layers,anadditionalconceptisprovidedinordertobypassthatrestrictionforresourcecriticaland/or NonAUTOSARcompliantsoftwarecomponents.TheComplexDeviceDriverprovidesan AUTOSARInterfacetotheapplicationlayerandhasdirectaccesstovaluesonthephysicallayer.This isusuallyusedfortheimplementationofcomplexsensororactuatordriversthatneeddirectcontrol overtheunderlyinghardware. 42.Howtoset,clear,toggleandcheckingasinglebitinC? UsethebitwiseORoperator(|)tosetabit.

number|=1<<x;

Thatwillsetbitx.

48 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Clearingabit UsethebitwiseANDoperator(&)toclearabit.

number&=~(1<<x);

Thatwillclearbitx.YoumustinvertthebitstringwiththebitwiseNOToperator(~),thenANDit. Togglingabit TheXORoperator(^)canbeusedtotoggleabit.

number^=1<<x;

Thatwilltogglebitx. Checkingabit YoudidntaskforthisbutImightaswelladdit. Tocheckabit,ANDitwiththebityouwanttocheck:

bit=number&(1<<x);

Thatwillputthevalueofbitxintothevariablebit. 42.WhatisWatchdogtimer? Awatchdogtimer(orcomputeroperatingproperly(COP)timer)isacomputerhardwareorsoftware timerthattriggersasystemresetorothercorrectiveactionifthemainprogram,duetosomefault condition,suchasahang,neglectstoregularlyservicethewatchdog(writingaservicepulsetoit, alsoreferredtoaskickingthedog,pettingthedog,feedingthewatchdogorwakingthe watchdog).Theintentionistobringthesystembackfromtheunresponsivestateintonormal operation.Watchdogtimerscanbemorecomplex,attemptingtosavedebuginformationontoa persistentmedium;i.e.informationusefulfordebuggingtheproblemthatcausedthefault.Inthis caseasecond,simpler,watchdogtimerensuresthatiftherstwatchdogtimerdoesnotreport completionofitsinformationsavingtaskwithinacertainamountoftime,thesystemwillresetwith orwithouttheinformationsaved.Themostcommonuseofwatchdogtimersisinembedded

49 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

systems,wherethisspecializedtimerisoftenabuiltinunitofamicrocontroller.

(http://automotivetechis.les.wordpress.com/2012/06 /untitled4.jpg) 43.Whatisthedierencebetween8bit16bitand32bitprocessor? Dierentfamiliesofmicrosvaryintheircapabilities.Thenumberofbitsjustreferstothewidthofthe datapipe,whichlimitstheprecisionofmath,althoughmanymicroswilleitheremulatehigherorder mathorhavespecialHWthatcanperformhigherprecisionmathfunctions. Thehistoricdierencehasbeenprice:8bitwascheapest,32bitwasexpensive.Thisisstilltruein generally,butthepriceof16bitpartshavecomedownsignicantly. Most8bitprocessorsareoldandrunonoldarchitectures,sotheytendtobeslower.Theyarealso mademorecheaply,sincethatiswherethecompetitionisatthe8bitpoint,andthismakesthem tendtowardsslowness.TheyalsotendtohavealowlimitonsupportedRAM/otherstorage,butthe actualamountdependsonthefamily. 16bitprocessorstendtofocusonpriceaswell,butthereisalargerangeofpartsavailable,someof whichhavefairlyhighperformanceandlargeamountsofonchipperipherals.Thesepartsusually performfasterthan8bitpartsonmathwheretheprecisionisgreaterthan8bits,andtendtohave moreaddressablememory. 32bitchipscompeteprimarilyonperformanceforanapplication.Thereisaconsiderablerangeof 32bitpartsavailable,eachtargetedatsomespecicapplication.Theytendtocomeloadedwith peripheralsandcompeteonfeaturecompleteness.Theyhavealargeamountofaddressablememory andtheperformancetendstobebetterthan16bitparts. 44.WhatisaFunctionPointer? Afunctionpointerisavariablethatstorestheaddressofafunctionthatcanlaterbecalledthrough thatfunctionpointer.Thisisusefulbecausefunctionsencapsulatebehavior.Forinstance,everytime youneedaparticularbehaviorsuchasdrawingaline,insteadofwritingoutabunchofcode,allyou needtodoiscallthefunction.Butsometimesyouwouldliketochoosedierentbehaviorsat dierenttimesinessentiallythesamepieceofcode. Example:int(*fp)(int,int);>Functionpointerreturninganinteger 45.SizeofDatatypes

50 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Name char short int(short) int

Description Characterorsmallinteger. ShortInteger. Integer.

Size* 1byte 2bytes 4bytes

Range* signed:128to127 unsigned:0to255 signed:32768to32767 unsigned:0to65535 signed:2147483648to 2147483647 unsigned:0to4294967295 signed:2147483648to 2147483647 unsigned:0to4294967295 trueorfalse +/3.4e+/38(~7digits) +/1.7e+/308(~15digits) +/1.7e+/308(~15digits)

long int(long) bool float double longdouble

Longinteger.

4bytes

Booleanvalue.Itcantakeoneoftwo values:trueorfalse. Floatingpointnumber. Doubleprecisionoatingpointnumber. Longdoubleprecisionoatingpoint number.

1byte 4bytes 8bytes 8bytes

46.Whatisthedierencebetweentypedef&Macros? Typedefisusedtocreateanewnametoanalreadyexistingdatatype.Redenethenamecreates conictwiththepreviousdeclaration. eg: typedefunsignedintUINT32 Macros[#dene]isadirectsubstitutionofthetextbeforecomplingthewholecode.Inthegiven example,itsjustatextualsubstitution.wherethereisaposibilityofredeningthemacro eg: #denechPointerchar* #undefchPointer #denechPointerint* Typedefareusedfordeclarationswhencomparewithmacro typedefscancorrectlyencodepointertypes.whereas#DEFINESarejustreplacementsdonebythe preprocessor. Forexample, 1. typedefchar*String_t; 2. #deneString_dchar* 3. String_ts1,s2;String_ds3,s4;

51 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

s1,s2,ands3arealldeclaredaschar*,buts4isdeclaredasachar,whichisprobablynotthe intention. 47.Whatisthedierencebetweenamacroandafunction? Macrosareessentiallyshorthandrepresentationsofarbitrarysectionsofthesourcecode,which makesthesourcecode,whileits(themacrotemplates)expansionreplaceseachofitspresenceprior tocompilation.WhateveristheretodowithMacros,itisdonebythepreprocessor,sothatthesource codeisreadyforcompilation.Functionisacallingroutine,whencealargeprogramisdividedinto separateportions,eachportiondoingaseparatejob,andpropercallingoftheseportionsindierent placescombinestheworksdonebythemintotherequiredcompleteoutput.Thusfunctionshave nothingtodowiththepreprocessingperiod,theyarejustcompiled.Tosomeextentfunctionand macroissimilar,foramacrocanoccasionallybeinvokedtoperformataskthatisgenerallyentrusted toafunction.Butthesimilarityendsthere. Thedierencesare: 1. Macroconsumeslesstime.Whenafunctioniscalled,argumentshavetobepassedtoit,those argumentsareacceptedbycorrespondingdummyvariablesinthefunction,theyareprocessed, andnallythefunctionreturnsavaluethatisassignedtoavariable(exceptforavoidfunction).If afunctionisinvokedanumberoftimes,thetimesaddup,andcompilationisdelayed.Onthe otherhand,themacroexpansionhadalreadytakenplaceandreplacedeachoccurrenceofthe macrointhesourcecodebeforethesourcecodestartscompiling,soitrequiresnoadditionaltime toexecute. 2. Functionconsumeslessmemory.Whileafunctionrepletewithmacrosmaylooksuccincton surface,priortocompilation,allthemacropresencesarereplacedbytheircorrespondingmacro expansions,whichconsumesconsiderablememory.Ontheotherhand,evenifafunctionis invoked100times,itstilloccupiesthesamespace.Hencefunctionismoreamenabletoless memoryrequirements 48.Whatisinlinefunction? Inlinefunctionistheoptimizationtechniqueusedbythecompilers.Onecansimplyprependinline keywordtofunctionprototypetomakeafunctioninline.Inlinefunctioninstructcompilertoinsert completebodyofthefunctionwhereverthatfunctiongotusedincode. Advantages: 1)Itdoesnotrequirefunctioncallingoverhead. 2)Italsosaveoverheadofvariablespush/poponthestack,whilefunctioncalling. 3)Italsosaveoverheadofreturncallfromafunction. 4)Itincreaseslocalityofreferencebyutilizinginstructioncache. 5)Afterinliningcompilercanalsoapplyintraproceduraloptmizationifspecied.Thisisthemost importantone,inthiswaycompilercannowfocusondeadcodeelimination,cangivemorestresson branchprediction,inductionvariableeliminationetc.. Disadvantages: 1)Mayincreasefunctionsizesothatitmaynottonthecache,causinglotsofcahcemiss. 2)Afterinliningfunctionifvariablesnumberwhicharegoingtouseregisterincreasesthantheymay createoverheadonregistervariableresourceutilization.

52 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

3)Itmaycausecompilationoverheadasifsomebodychangescodeinsideinlinefunctionthanall callinglocationwillalsobecompiled. 4)Ifusedinheaderle,itwillmakeyourheaderlesizelargeandmayalsomakeitunreadable. 5)Ifsomebodyusedtoomanyinlinefunctionresultantinalargercodesizethanitmaycause thrashinginmemory.Moreandmorenumberofpagefaultbringingdownyourprogram performance. 6)Itsnotusefulforembededsystemwherelargebinarysizeisnotpreferredatallduetomemory sizeconstraints 49.Whatisthedierencebetweenamacroandainlinefunction? Macros: 1.inputargumentdatatypecheckingcantbedone. 2.compilerhasnoideaaboutmacros 3.Codeisnotreadable 4.macrosarealwaysexpandedorreplacedduringpreprocessing,hencecodesizeismore. 5.macrocantreturn. Inlinefunction: 1.inputargumentdatatypecanbedone. 2.compilerknowsaboutinlinefunctions. 3.codeisreadable 4.inlinefunctionsaremaynotbeexpandedalways 5.canreturn. 50.PreprocessorStatements#ifdef,#else,#endif Theseprovidearapidwaytoclipoutandinsertcode. Consider;

#defineFIRST main() { inta,b,c; #ifdefFIRST a=2;b=6;c=4; #else printf("Entera:"); scanf("%d",&a); printf("Entera:"); scanf("%d",&a);

53 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

printf("Entera:"); scanf("%d",&a); #endif additonalcode

NotethatifFIRSTisdened(whichitisintheabove)thevaluesofa,bandcarehardcodedtovalues of2,6and4.Thiscansavealotoftimewhendevelopingsoftwareasitavoidstediouslytyping everythingineachandeverytimeyourunyourroutine.WhenFIRSTisdened,allthatispassedto thecompileristhecodebetweenthe#ifdefandthe#else.Thecodebetweenthe#elseandthe#endifis notseenbythecompiler.Itisasifitwereallacomment. Onceyouhaveyourroutineworking,anddesiretoinserttheprintfandscanfs,allthatisrequiredis togobackanddeletethethe#deneFIRST.Now,thecompilerdoesnotseethe;

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

ThereceiverscalculatetheCRCinthesamewayasthetransmitterasfollows: 1. Themessageisregardedaspolynomandisdividedbythegeneratorpolynom: 15 x +x14+x10+x8+x7+x4+x3+1. 2. Thedivisionrestofthismodulo2divisionistheCRCsequencewhichistransmittedtogetherwith themessage. 3. ThereceiverdividesthemessageinclusivetheCRCsequencebythegeneratorpolynom.

ACRCerrorhastobedetected,ifthecalculatedresultisnotthesameasthatreceivedintheCRC sequence.InthiscasethereceiverdiscardsthemessageandtransmitsanErrorFrametorequest retransmission.


54 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

51.DierencebetweenstaticanddynamicRAM? StaticRAM(SRAM)Highcost&Fast 1.4timesmoreexpensive 2.Verylowaccesstime 3.Canstoreasmuch 4.InformationstoredonRSipops 5.Noneedforrefreshing DynamicRAM(DRAM)Lowcost&slow 1.Lowcost 2.Consumeslesspower 3.Canstore4timesasmuch 4.InformationstoredonFETtransistors 5.Needstoberefreshed CANoeToolQuestions: WhatisdierencethebetweenIGandGblockinCANalyzer/CANoetool? Answer:TherearetwolimitationstotheGeneratorblockthatlimititseectivenessincomplextasks. Theblockismisleadingforsomepeoplebecauseitrequiresmultiplewindowsforsettingupthe transmitmessagelist.ThesecondproblemistheblocksettingshavetobesetbeforetheCANalyzer measurementstarts.Nochangescanbemadeifthemeasurementisrunning. Fortunately,CANalyzerhasanothertransmissionblockthateliminatesbothpracticallimitations:the InteractiveGeneratorblock(IG).TheIGblockcombinesthecongurationwindowsoftheGenerator blockintoonewindow;therefore,everythingcanbesetupinonespot.Inaddition,changescanbe madewiththeIG. WithoutCAPL,canwesimulatetheotherECUsCANMessagesexceptTestECUintheCAN SimulationNetworkinCANoetoolwithoutusingIGorGblocks. HowtochangethebaudrateinCANoewithoutchangingthecode? Thebitratemaybechangedbyeitherchangingtheoscillatorfrequency,whichisusually restrictedbytheprocessorrequirements,orbyspecifyingthelengthofthebitsegmentsintime quantumandtheprescalervalue. InCanoetool,wecanchangethebustimingregister0&1valuesforcorrectingthebaudrate. InAutosar,wecanusepostbuildcongurationforCANbaudratevalues. Whatisenvironmentvariable? EnvironmentvariablesaredataobjectsglobaltotheCANoeenvironmentandareusedtolinkthe functionsofaCANoepaneltoCAPLprograms.

55 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

WhatisHILandSILtesting? Answer:Hardwareintheloop(HIL)simulationisatechniquethatisusedinthedevelopmentand testofcomplexrealtimeembeddedsystems.HILsimulationprovidesaneectiveplatformby addingthecomplexityoftheplantundercontroltothetestplatform.Thecomplexityoftheplant undercontrolisincludedintestanddevelopmentbyaddingamathematicalrepresentationofall relateddynamicsystems.Thesemathematicalrepresentationsarereferredtoastheplant simulation.Theembeddedsystemtobetestedinteractswiththisplantsimulation. HardwareIntheLoopSystemisaneectiveplatformfordevelopingandtestingcomplexrealtime embeddedsystems.HILsystemprovidesthecomplexityoftheplantundercontrolusing mathematicalrepresentation,calledplantsimulation,ofallrelateddynamicsystems.Italso includeselectricalemulationofsensorsandactuatorswhichactastheinterfacebetweentheplant simulationandtheembeddedsystemundertest. AdvantagesofHILSystem ProvidesCostSavingsbyShortenedDevelopmenttime Complete,consistenttestcoverage. Supportsautomatedtesting Enablestestingthehardwarewithoutbuildingaplantprototype Simulatorperformstestoutsidethenormalrangeofoperation Supportsreproducibletestrunsthatcanassistinuncoveringandtrackingdownhardtond problems. Enablestestingwithlessriskofdestroyingthesystem SIL:SILreferstothekindoftestingdonetovalidatethebehavioroftheCcodeusedinthe controller.Thatcodecanbeautogeneratedfromthemodelusedinalgorithmdevelopment. EmmeskayhasadeepunderstandingofSILtestingandautocodegenerationfromthemanySIL projectswehaveperformedforourcustomers. TestingandValidation PlantmodeldevelopedinvehiclesimulationenvironmentisimportedtoSimulinkasalibrary. Controlleristestedinloopwiththeplantfordierentroutesandspeedproles. ControlleristestedfordierentfaultmodesofthesystemusingGUIVisualConnex RTOSQuestion: WhatisRTOS? RealTimeOperatingSystemisamultitaskingoperatingsystemintendedforrealtimeapplications.It isusedoneverydevice/systemneedingrealtimeoperationsthatmeansoperationsbasednotonlyon correctnessbutalsouponthetime(clockcycles)inwhichtheyareperformed. Ingeneral,anoperatingsystem(OS)isresponsibleformanagingthehardwareresourcesofa computerandhostingapplicationsthatrunonthecomputer.AnRTOSperformsthesetasks,butis alsospeciallydesignedtorunapplicationswithveryprecisetimingandahighdegreeofreliability. Thiscanbeespeciallyimportantinmeasurementandautomationsystemswheredowntimeiscostly oraprogramdelaycouldcauseasafetyhazard.Tobeconsideredrealtime,anoperatingsystem
56 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

musthaveaknownmaximumtimeforeachofthecriticaloperationsthatitperforms(oratleastbe abletoguaranteethatmaximummostofthetime).SomeoftheseoperationsincludeOScallsand interrupthandling.Operatingsystemsthatcanabsolutelyguaranteeamaximumtimeforthese operationsarecommonlyreferredtoashardrealtime,whileoperatingsystemsthatcanonly guaranteeamaximummostofthetimearereferredtoassoftrealtime. Example:Imaginethatyouaredesigninganairbagsystemforanewmodelofcar.Inthiscase,a smallerrorintiming(causingtheairbagtodeploytooearlyortoolate)couldbecatastrophicand causeinjury.Therefore,ahardrealtimesystemisneeded;youneedassuranceasthesystemdesigner thatnosingleoperationwillexceedcertaintimingconstraints.Ontheotherhand,ifyouwereto designamobilephonethatreceivedstreamingvideo,itmaybeoktoloseasmallamountofdata occasionallyeventhoughonaverageitisimportanttokeepupwiththevideostream.Forthis application,asoftrealtimeoperatingsystemmaysuce.AnRTOScanguaranteethataprogram willrunwithveryconsistenttiming.Realtimeoperatingsystemsdothisbyprovidingprogrammers withahighdegreeofcontroloverhowtasksareprioritized,andtypicallyalsoallowcheckingto makesurethatimportantdeadlinesaremet. HowRealTimeOSsDierfromGeneralPurposeOSs? OperatingsystemssuchasMicrosoftWindowsandMacOScanprovideanexcellentplatformfor developingandrunningyournoncriticalmeasurementandcontrolapplications.However,these operatingsystemsaredesignedfordierentusecasesthanrealtimeoperatingsystems,andarenot theidealplatformforrunningapplicationsthatrequireprecisetimingorextendeduptime.This sectionwillidentifysomeofthemajorunderthehooddierencesbetweenbothtypesofoperating systems,andexplainwhatyoucanexpectwhenprogrammingarealtimeapplication.

Interruptlatencyismeasuredastheamountoftimebetweenwhenadevicegeneratesaninterrupt andwhenthatdeviceisserviced.Whilegeneralpurposeoperatingsystemsmaytakeavariable amountoftimetorespondtoagiveninterrupt,realtimeoperatingsystemsmustguaranteethatall interruptswillbeservicedwithinacertainmaximumamountoftime.Inotherwords,theinterrupt latencyofrealtimeoperatingsystemsmustbebounded UnansweredInterviewQuestions Ifyouknowcommentasreply) WhatistheuseofPassiveerrornode? ErrorPassivereceiverscannolongerinterruptthedatatransferasarecessiveErrorFlagdoesnot inuencethebuslevels.AnErrorPassivetransmittercanstillinterruptitsownmessagebysendinga passiveErrorFlag.Attention,ifoneReceiverisinerrorpassivemodenodataconsistencyis guaranteedanymore. Howtondthebugincodeusingdebuggerifpointerispointingtoaillegalvalue? IftwoCANmessageswithsameIDsendingatasametime,dierentdatawhichcannodewill

57 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

gainarbitration?Howtotestit? Isitpossibletodeclarestructanduniononeinsideother?Explainwithexample 1. 2. 3. 4. 5. 6. 7. 8. SpiandI2Cdierence.? WhatisUDSadvantages? Whatiscrosscompiler Unit/integration/alltestings. Regressiontesting. Testcasetypes. Malloccalloc FunctionpointersAdvantagewhereitisused?

HowmanycandatabaselesarerequiredforCANNetworksimulationinCANoetool. whatisthedierencebetweenCANalyzer,CANoeandCANapetools? MentionthefewusesoftheCANoetool? whatisapanelisCANoeToolanditsUse? WhyCAPLscriptingisusedinCANoetool? IsitpossibletosimulateotherECUsExceptTestECUwithoutCAPLScriptinginCANoetool? whatispurposeofCCPprotocolwhichisalsousedinCANapetool? EmbeddedDevelopmentDocuments: Introduction_to_prog_embedded_systems(http://automotivetechis.les.wordpress.com/2012/06 /lecinto_to_prog_embedded_systems.pdf) youtubehttp://www.youtube.com/watch?v=sw3ADKPo1Uo&feature=player_detailpage%5D (http://www.youtube.com/watch?v=sw3ADKPo1Uo&feature=player_detailpage%5D)

PrateekDewangan JULY1,2013@3:38PM ImustSaythanksforthisarticel REPLY Vijaisankar JULY24,2013@6:54AM superbgenerallycovered.andtheperformanceofacandiadatedependsonhowhepresentsand hispastexperience.Thanksalot.

58 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

REPLY pavan AUGUST2,2013@8:54AM trulygood Thanks. REPLY Sonali AUGUST2,2013@11:51AM Thankyouverymuchforthisarticalitisreallyhelpful. REPLY

BlogatWordPress.com.|TheiTheme2Theme. Follow

PoweredbyWordPress.com

59 of 59

8/6/2013 4:17 PM

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

A BRIEF LIST OF MATLAB COMMANDS Some Basic Commands (Note command syntax is case-sensitive!) matlab quit exit who whos clear clear x ... save load save save load ! loads the program matlab into your workspace. quits matlab, returning you to the operating system. same as quit. lists all of the variables in your matlab workspace. list the variables and describes their matrix size. deletes all matrices from active workspace. deletes the matrix x from active workspace. the ellipsis defining a line continuation is three successive periods. saves all the matrices defined in the current session into the file, matlab.mat. loads contents of matlab.mat into current workspace. filename saves the contents of workspace into filename.mat filename x y z saves the matrices x, y and z into the file titled filename.mat. 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) hist(x) 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).) creates a histogram. This differs from the bargraph
Page 1 of 26

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

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

in that frequency is plotted on the vertical axis. 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. mesh(z) 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
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 2 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

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) size(x) rand randn rand(A) returns the number elements in a vector. returns the size m(rows) and n(columns) of matrix x. returns a random number between 0 and 1. returns a random number selected from a normal distribution with a mean of 0 and variance of 1. 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 single line of code follows the below order: Precedence Operation
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 3 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

1 2 3 4

parentheses exponentiation, left to right multiplication and division, left right addition and subtraction, left right

MATRIX ALGEBRA In matrix multiplication, the elements of the product, C, of two 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 right matrix (B). The resulting product, matrix C, has an order for which the 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 the number of columns in the second (right) matrix (B). It is clear that A*B IS NOT NECESSARILY EQUAL TO B*A! The PRODUCT OF A SCALAR AND A MATRIX is a matrix in which every element of the matrix has been multiplied by the scalar. ARRAY PRODUCTS Sometimes it is desired to simply multiply or divide each element of an matrix by the corresponding element of another matrix. These are called 'array operations" in 'matlab'. Array or element-by-element operations are executed when the operator is preceded by a '.' (period). Thus a .* b a ./ b a .\ b a .^ b multiplies each element element of b divides each element of of b divides each element of of a raise each element of a of a by the respective a by the respective element b by the respective element 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 is simply G1' * G2 {Note G1' is nx1 and G2 is 1xn}
Page 4 of 26

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

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

and the result is a square matrix in contrast to the scalar result for the inner product. DON'T CONFUSE THE OUTER PRODUCT WITH THE VECTOR PRODUCT IN MECHANICS! If the two vectors are column vectors, the outer product must be formed by the product of one vector times the 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 b/a returns a equation returns a equation column vector solution for the matrix ax=b where a is a coefficient matrix. row vector solution for the matrix xa=b where a is a coefficient matrix.

Some basic commands you will need: matlab quit exit who whos loads the program matlab into your workspace quits matlab, returning you to the operating system same as quit lists all of the variables in your matlab workspace list the variables and describes their matrix size

NOTE - When using the workstations, clicking on UP ARROW will recall previous commands. If you make a mistake, the DELETE key OR the backspace key may be used to correct the error; however, one of these two keys may be inoperable on particular systems. 'matlab' uses variables that are defined to be matrices. A matrix is a collection of numerical values that are organized into a specific configuration of rows and columns. The number of rows and columns can be any number, for example, 3 rows and 4 columns define a 3 x 4 matrix which has 12 elements in total. A scalar is represented by a 1 x 1 matrix in matlab. A vector of n dimensions or elements can be represented by a n x 1 matrix, in which case it is called a column vector, or a vector can be represented by a 1 x n 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 variable name, but '1x' is illegal. 'supercalafragilesticexpealladotious' can be a variable name; however, only the first 19 characters will be 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 are bounded by brackets ......[ ].
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 5 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

c = 5.66

or

c = [5.66]

c is a scalar or a 1 x 1 matrix x is a row vector or 1 x 3 matrix x1 is column vector or 4 x 1 matrix

x = [ 3.5, 33.22, 24.5 ] x1 = [ 2 5 3 -1] A = [ 1 2 2 -2 0 3 5 4 4 2 5 9 ]

A is a 4 x 3 matrix

An individual element of a matrix can be specified with the notation A(i,j) or Ai,j for the generalized element, or by A(4,1)=5 for a specific element. When 'matlab' prints a matrix on the monitor, it will be organized according to the size specification of the matrix, with each row appearing on a unique row of the monitor screen and with each column aligned vertically and right-justified. The numerical values that are assigned to the individual elements of a matrix can be entered into the variable assignment in a number of ways. The simplest way is by direct keyboard entry; however, large data sets may be more conveniently entered through the use of stored files or by generating the element values using matlab expressions. First, we will look at the use of the keyboard for direct entry. KEYBOARD DEFINITION OR ENTRY FOR A MATRIX A matrix can be defined by a number of matlab expressions. Examples are 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 of numbers, and notice that commas or blanks may be used as delimiters between the fields defining the elements of the matrix. Blanks used around the = sign and the brackets are superfluous; however, they sometimes 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 can be defined y = [ 0 2 2 3 5 -3 6 4 ]
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 6 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

or y = [ 0 2 2 3 ; 5 -3 6 4 ] The semicolon ";" is used to differentiate the matrix rows when they appear on a single line for data entry. The elements of a matrix can be defined with algebraic expressions placed 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 The expression x(5) = 8 creates x = [ 2 4 -1 0 8 ] Notice that the value "0" is substituted for x(4) which has not been explicitly defined. Recalling the definition of matrix, y, above, the expressions c = [ 4 5 6 z = [ y;c ] creates z = [ 0 2 5 -3 4 5 2 6 6 3 4 3 ] 3 ] 4 -1 5 8 ]

Note that every time a matrix is defined and an 'enter' keystroke is executed, matlab echoes back the result. TO CANCEL THIS ECHO, THE MATLAB COMMAND LINE CAN INCLUDE A SEMICOLON AT THE END OF THE LINE BEFORE THE KEYSTROKE 'ENTER'. z = [ y ; c ] ; LINE CONTINUATION Occasionally, a line is so long that it can not be expressed in the 80 spaces available on a line, in which case a line continuation is needed. In matlab, the ellipsis defining a line continuation is three successive periods, as in "...". Thus
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 7 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

4 + +

5 1 + 5

+ +

3 ... 10 +

2 ...

gives the result ans = 30 Notice that in this simple arithmetic operation, no matrix was defined. When such an operation is executed in matlab, the result is assigned to the matrix titled "ans". A subsequent operation without an assignment to a specific matrix name will replace the results 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 matlab commands 'who' and whos' before you 'quit'. Note that each of these commands lists the matrices you have defined in this session on the computer. The command 'whos' also tells you the properties of each matrix, 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 you quit, all of the matrices that have been defined will be saved in a file titled matlab.mat stored in your workspace. Should you desire to save specific matrices during any session, the command 'save' followed by the name of the matrix can be executed. More detail 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 the matrices, and check your results using the 'whos' statement. 1. 2. 3. 4. a = [1,0,0,0,0,1] b = [2;4;6;10] c = [5 d= [3 5 9 e = [3 4 7 10 ] 5 0 6. 7. 10 3; 0; 3 0 9 0 ... 9 8 ] 3 5; 6 2 -3]

5.

t = [4 24 9] q = [t 0 t] x = [ 3 6 ]
Page 8 of 26

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

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

y = [d;x] z = [x;d] 8. 9. 10. r = [ c; x,5] v = [ c(2,1); b ]

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. loads contents of matlab.mat into current workspace

load

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 clear

erases the matrix 'x' from your workspace erases ALL matrices from your workspace

NOTE - When using PROMATLAB on a workstation, files are stored in the directory from which you invoked the 'matlab' command. When using the workstation, create a matlab subdirectory titled 'matlab' or some similar name. Thereafter, store all files and conduct all matlab sessions in that subdirectory. ASCII FILES An ASCII file is a file containing characters in ASCII format, a format that is independent of 'matlab' or any other executable program. Using ASCII format, you can build a file using a screen editor or a wordprocessing program, for example, that can be read and 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 of writing a file in ASCII format, you simply prepare a matrix file for which EACH ROW OF THE MATRIX IS A UNIQUE LINE IN THE FILE, with the elements in the row separated by blanks. An example is the 3 x 3 matrix 2 3 6 3 -1 0 7 0 -2 If these elements are formatted as described above and stored in a filename titled, for example, x.dat, the 3 x 3 matrix 'x' can be
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 9 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

loaded into 'matlab' by the command load x.dat Open the Text Editor window on your workstation. Build a 3x3 matrix 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 strongly recommended here to distinguish the file from other data files, such as the .mat files which will be described below. Of course if you define the file with the .dat or any other suffix, you must use that suffix when downloading the file to 'matlab' with the 'load' command. Remember, the file must be stored in the directory in which you are executing matlab. In the above example, it is assumed that this directory is titled 'matlab'. Now go to a window in which matlab is opened. We desire to load the matrix x into matlab. We might wonder if the file x.dat is actually stored in our matlab directory. To review what files are stored therein, the unix command 'ls' can be evoked in matlab by preceding the command with an exclamation mark, ! . Type the command ! ls Matlab will list all of the files in your directory. find one titled "x.dat". Now, type the command load x.dat The 3x3 matrix defined above is now down-loaded into your working space in matlab. To ensure that is so, check your variables by typing 'who' or 'whos'. FILES BUILT BY MATLAB....THE .mat FILE If at any time during a matlab session you wish to store a matrix that 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 and this can be omitted by the user when describing the filename. If the matrix 'x' has been defined in the workspace, it can be stored 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
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 10 of 26

You should

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

named, for example, 'stuff' can be a file that contains the matrix 'x'. Any number of matrices can be stored under the filename. Thus the command string save stuff x y z

will store the matrices x, y and z in the file titled 'stuff'. The file will automatically have the suffix .mat added to the filename. If, during a session, you type the command 'save' with no other string, all of the current matrices defined in your workspace will be stored in the file 'matlab.mat'. The load command when applied to .mat files follows the same format as discussed above for ASCII files; however, you can omit the file suffix '.mat' when loading .mat files to your workspace. COLON OPERATOR The colon operator ' : ' is understood by 'matlab' to perform special and useful operations. If two integer numbers are separated by a colon, 'matlab' will generate all of the integers between these 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 two colons, the middle number is interpreted to be a "range" and the first 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 0 -2 The command y = x(:,1) creates the column vector y = [ 2 0 -2 6 8 1 7 5 -6 ]

] yy = x(:,2)

and creates yy = [ 6
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 11 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

1 5 ] The command z = x(1,:) creates the row vector z = [ 2 6 8 ]

The colon operator is useful in extracting smaller matrices from larger matrices. If the 4 x 3 matrix c is defined by c = [ -1 0 1 1 1 -1 0 0 Then d1 = c(:,2:3) creates a matrix for which all elements of the rows from the 2nd and third columns are used. The result is a 4 x 2 matrix d1 = [ 0 1 -1 0 0 0 0 2 ] 0 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 and 4th row of c and the columns are defined by the 1st and 2nd columns of the matrix, c. d2 = [ 1 0 -1 0 ]

USING THE CLEAR COMMANDS Before quitting this session of 'matlab', note the use of the commands 'clear' and 'clc'. Note that 'clc' simply clears the screen, but does not clear or erase any matrices that have been defined. The command 'clear' erase or removes matrices from your workspace. Use this command with care. NOTE THE COMMAND 'CLEAR' WITHOUT ANY MODIFYING STRING WILL ERASE ALL MATRICES IN YOUR WORKSPACE. PROBLEMS Define the 5 x 4 matrix, g. g = [ 0.6 1.5 2.3 -0.5
Page 12 of 26

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

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

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 check your results for content and size using 'matlab'. 1. 2. 3. 4. 5. 6. 7. a = g(:,2) b = g(4,:) c = [10:15] d = [4:9;1:6] e = [-5,5] f= [1.0:-.2:0.0] 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) loglog(x,y) grid plots x vs log(y) plots log(x) vs log(y)

creates a grid on the graphics plot places a title at top of graphics plot

title('text')

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).)

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

Page 13 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

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 to create graphic plots. Here we introduce the elementary ideas for simply presenting a graphic plot of two vectors. More complicated and powerful ideas with graphics can be found in the 'matlab' documentation. A Cartesian or orthogonal x,y plot is based on plotting the x,y data pairs from the specified vectors. Clearly, the vectors x and y must have the same number of elements. Imagine that you wish to 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 be used in these tutorials without explanation if they take on an unambiguous meaning consistent with past experience. Here it is observed that operating on a matrix with these functions simply creates a matrix in which the elements are based on applying the function to each corresponding element of the argument. Of course the symbols x,y are arbitrary. If we wanted to plot temperature on the ordinate and time on the abscissa, and vectors for temperature and time were loaded in 'matlab', the command would be plot(time,temperature) Notice that the command plot(x,y) opens a graphics window. If you now execute the command 'grid', the graphics window is redrawn. (Note you move the cursor to the command window before typing new commands.) To avoid redrawing the window, you may use the line continuation ellipsis. Consider plot(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 of code, such as the above, the use of line continuation can be frustrating. In a future lesson, we will learn how to create batch files (called '.m' files) for executing a series of 'matlab' commands. This approach gives you better opportunity to return to the command string and edit errors that have been created. Having defined the vectors x and y, construct semilog and loglog plots using these or other vectors you may wish to create. Note
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 14 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

in particular what occurs when a logarithmic scale is selected for a vector that has negative or zero elements. Here, the vector x has a zero element (x(1)=0). The logarithm of zero or any negative number is undefined and the x,y data pair for which a zero or negative number occurs is discarded and a warning message provided. Try the commands plot(x) and plot(y) to ensure you understand how they differ from plot(x,y). Notice that 'matlab' draws a straight line between the datapairs. If you desire to see a relatively smooth curve drawn for a rapidly changing function, you must include a number of data points. For example, consider the trigonometric function, sin(x1) (x1 is selected as the argument here to distinguish it from the vector 'x' that was defined earlier. ) Plot sin(x1) over the limits 0 <= x1 <= pi. First define x1 with 5 elements, x1 = 0 : pi/4 : pi y1 = sin(x1) plot(x1,y1) Now, repeat this after defining a new vector for x1 and y1 with 21 elements. (Note the use of the semicolon here to prevent the printing and scrolling on the monitor screen of a vector or matrix with 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 Cartesian x-y plots; however, the arguments are the angle 'theta' in radians measured CCW from the horizontal (positive-x) axis, and the length of the radius vector extended from the origin along this angle. Polar plots do not allow the labeling of axes; however, notice that the scale for the radius vector is presented along the vertical and when the 'grid' command is used the angles-grid is presented in 15degree segments. The 'title' command and the 'text' commands are functional 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 the vectors x,y that were defined earlier. Create bar and stair graphs using these or other vectors you may define. Of course the 'title' and 'text' commands can be used with bar and stair graphs.
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 15 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

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 open with the 'hold' command and execute a subsequent plotting command. x1=0:.05*pi:pi; y1=sin(x1); plot(x1,y1) hold y2=cos(x1); plot(x1,y2) The "hold" command will remain active until you turn it off with the command 'hold off'. You can create multiple graphs by using multiple arguments. In addition to the vectors x,y created earlier, create the vectors a,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 matrices rather than simple vectors in the argument. If the arguments of the 'plot' command are matrices, the COLUMNS of y are plotted on the ordinate against the COLUMNS of x on the abscissa. Note that x and y must be of the same order! If y is a matrix and x is a vector, the rows or columns of y are plotted against the elements of x. In this instance, the number of rows OR columns in the matrix must 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. Augment the 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 pairs described by the vectors used in the 'print' command. You may wish to present data points and omit any connecting lines between these points. Data points can be described by a variety of characters ( . , + , * , o and x .) The following command plots the x,y data as 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')

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

Page 16 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

Lines can be colored and they can be broken to make distinctions among more than one line. Colored lines are effective on the color monitor and color printers or plotters. Colors are useless on the common printers used on this network. Colors are denoted in 'matlab' by the symbols r(red), g(green), b(blue), w(white) and i(invisible). The following command plots the x,y data 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 the current graphics widow to the local printer. You may wish to save in a graphics file, a plot you have created. To do so, simply append to the 'print' command the name of 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 include the .ps suffix, as matlab will do this. When you list the files in your matlab directory, it is convenient to identify any graphics files by simply looking for the files with the .ps suffix. If you desire to print one of these postscript files, you can conveniently "drag and drop" the file from the file-manager window into 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. returns the minimum of x (see max(x) for details). 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.

min (x) mean(x)

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. same as sum(x), only returns the product of elements. 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 17 of 26

prod(x) std(x)

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

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

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. plots a histogram of the elements of vector, x. Ten bins are scaled based on the max and min values.

hist(x)

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 perform simple 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 exercise by creating a 12x3 matrix that represents a time history of two stochastic temperature measurements. Load these data into a matrix called 'timtemp.dat' using an editor to build an ASCII file. Time(sec) 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 Temp-T1(K) 306 305 312 309 308 299 311 303 306 303 306 304 Temp-T2(K) 125 121 123 122 124 129 122 122 123 127 124 123

Execute the commands at the beginning of the lesson above and observe the results. Note that when the argument is 'timtemp', a matrix, 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, the command 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 is desired, the standard deviation is squared. The command
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 18 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

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

Sometimes it is convenient to write a number of lines of 'matlab' code before executing the commands. We have seen how this can be accomplished using the line continuation ellipsis; however, it was noted in this approach that any mistake in the code required the entire string to be entered again. Using an m-file we can write a number of lines of 'matlab' code and store it in a file whose name we select with the suffix '.m' added. Subsequently the command string or file content can be executed by invoking the name of the file while in 'matlab'. This application is called a SCRATCH 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 of functions. We can write functions of our definition to evaluate parameters of our particular interest. This application of m-files is called FUNCTION FILES. SCRATCH FILES A scratch file must be prepared in a text editor in ASCII format and stored in the directory from which you invoked the command to download 'matlab'. The name can be any legitimate file name with the '.m' suffix. As an example, suppose we wish to prepare a x-y plot of the function 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 code below. (Note the use of the '%' in line 1 below to create a
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 19 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

comment. Any text or commands typed on a line after the'%' will be treated 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 the command 'explot' the x-y plot of the damped exponential sine function will appear. FUNCTION FILES Suppose that you wish to have in your 'matlab' workspace a function that calculates the sine of the angle when the argument is in degrees. The matlab function sin(x) requires that x be in radians. A function can be written that use the 'matlab' sin(x) function, where x is in radians, to accomplish the objective of calculating the sine of an argument expressed in degrees. Again, as in the case of the scratch file, we must prepare the file in ASCII 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 THE FUNCTION. The following code will accomplish our objective. Note that the first line must always begin with the word "function" followed by the name of the function expressed as " y = function-name". Here the function name is "sind(x)". This is the name by which we will call 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 the first line of the file the word 'function', followed by y = function call, here 'sind' with the function argument in parentheses, 'x' is the function call. Thus, function y=sind(x) Now every time we type sind(x) in 'matlab', it will return the value of the sine function calculated under the assumption that x is in degrees. Of course any matrix or expression involving a matrix can be written in the argument. ALGEBRAIC OPERATIONS IN MATLAB

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

Page 20 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

Scalar Calculations. The common arithmetic operators used in spreadsheets and programming languages such as BASIC are used in 'matlab'. In addition a distinction is made between right and left division. 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 these operators the precedence or order of the calculations follows the below order: Precedence 1 2 3 4 Operation parentheses exponentiation, left to right multiplication and division, left right 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 nonscalar matrices require additional rules for the application of these operators!!) For example, 3*4 ans=12 executed in 'matlab' gives

4/5 executed in 'matlab' gives ans=.8000 4\5 executed in 'matlab' gives ans=1.2500 x = pi/2; y = sin(x) y = 1 z = 0; w = exp(4*z)/5 z= .2000 executed in 'matlab' gives executed in 'matlab" gives

Note that many programmers will prefer to write the expression for w above in the format w = (exp(4*x))/5 which gives the same result and is sometimes less confusing when the string of arithmetic operations is long. Using 'matlab', carry out some simple arithmetic operations with scalars you define. In doing 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 in the documentation. Matrix Calculations. Because matrices are made up of a number of elements and not a single number (except for the 1x1 scalar matrix), the ordinary rules of commutative, associative and distributive operations in arithmetic do not always follow.
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 21 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

Moreover, a number of important but common-sense rules will prevail in matrix algebra and 'matlab' when dealing with nonscalar quantities. Addition and Subtraction of Matrices. Only matrices of the SAME ORDER can be added or subtracted. When two matrices of the same order are added or subtracted in matrix algebra, the individual elements are added or subtracted. Thus the distributive rule applies. 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 gives C = 3 5 5 -1 1 7 7 5 1 and C = B + A

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 have the same order. (x is a 1x3 matrix and y is a 3x1 matrix.) Adding any number of 1x1 matrices or scalars is permissible and follows the ordinary rules of arithmetic because the 1x1 matrix is a scalar. Adding two vectors is permissible so long as each is a row vector (1xn matrix) or column vector (nx1 matrix). Of course any number of vectors can be added or subtracted, the result being the arithmetic sum of the individual elements in the column or row vectors. Square matrices can always be added or subtracted so long as they are of the same order. A 4x4 square matrix can not be added to a 3x3 square matrix, because they are not of the same order, although both matrices are square. Multiplication of Matrices. Matrix multiplication, though straightforward in definition, is more complex than arithmetic multiplication because each matrix contains a number of elements. Recall that with vector multiplication, the existence of a number
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 22 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

of elements in the vector resulted in two concepts of multiplication, the scalar product and the vector product. Matrix multiplication has its array of special rules as well. In matrix multiplication, the elements of the product, C, of two 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 right matrix (B). The resulting product, matrix C, has an order for which the 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 the number of columns in the second (right) matrix (B). It is clear that A*B IS NOT NECESSARILY EQUAL TO B*A! It is also clear that A*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 c12 c21 c22 = = = = a11*b11 a11*b12 a21*b11 a21*b12 + + + + a12*b21 a12*b22 a22*b21 a22*b22

Carry out the calculations by hand and verify the result using 'matlab'. Next, consider the following matrix product of a 3x2 matrix X and a 2x4 matrix Y. X = [2 Y = [5 3 ; 4 -1 ; 0 -6 7 2 ; 1 7]; 2 3 6];

First, note that the matrix product X*Y exists because X has the same number of columns (2) as Y has rows (2). (Note that Y*X does NOT exist!) If the product of X*Y is called C, the matrix C must be a 3x4 matrix. Again, carry out the calculations by hand and verify the result using 'matlab'. Note that the PRODUCT OF A SCALAR AND A MATRIX is a matrix in which every element of the matrix has been multiplied by the scalar. Verify this by recalling the matrix X defined above, and carry out the product 3*X on 'matlab'. (Note that this can be written X*3 as well as 3*X, because quantity '3' is scalar.) ARRAY PRODUCTS Recall that addition and subtraction of matrices involved addition or subtraction of the individual elements of the matrices. Sometimes it is desired to simply multiply or divide each element of an matrix by the corresponding element of another matrix. These are called 'array operations" in 'matlab'. Array or element-byelement operations are executed when the operator is preceded by a
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 23 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

'.' (period). a .* b a ./ b a .\ b a .^ b

Thus multiplies each element element of b divides each element of of b divides each element of of a raise each element of a of a by the respective a by the respective element b by the respective element by the respective b element

For example, if matrices G and H are defined G = [ 1 H = [-4 3 0 5; 2 3; 1 0 36 4 9 6]; 8]; 15 48 ]

G .* H = [ -4 2

TRANSPOSE OF A MATRIX 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, '. Recalling the matrix G G' = [ 1 3 5 2 4 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 that of creating a column vector from a row vector, or a row vector from a column vector. INNER (SCALAR) PRODUCT OF TWO VECTORS The scalar or inner product of two row vectors, G1 and G2 is found as follows. Create the row vectors for this example by decomposing the matrix G defined above. G1 = G(1,:) G2 = G(2,:) Then the inner product of the 1x3 row vector G1 and the 1x3 row vector 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 inner product must be formed by the matrix product of the transpose of a column vector times a column vector, thus creating an operation in which a 1 x n matrix is multiplied with a n x 1 matrix. In summary, note that the inner product must always be the product of a row vector times a column vector. OUTER PRODUCT OF TWO VECTORS
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 24 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

If two row vectors exist, G1 and G2 as defined above, the outer 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 result for the inner product. DON'T CONFUSE THE OUTER PRODUCT WITH THE VECTOR PRODUCT IN MECHANICS! If the two vectors are column vectors, the outer product must be formed by the product of one vector times the transpose of the second! OTHER OPERATIONS ON MATRICES As noted above, many functions that exist can be applied directly to a matrix by simply allowing the function to operate on each element of the matrix array. This is true for the trigonometric functions and their inverse. It is true also for the exponential function, ex, exp(), and the logarithmic functions, log() and log10(). Exponential operations (using ^) on matrices are quite different from their use with scalars. If W is a square matrix W^2 implies W*W which is quite different from W.*W. Be certain of your intent before raising a matrix to an exponential power. Of course W^2 only exists if W is a square matrix. SPECIAL MATRICES A number of special functions exist in 'matlab' to create special or unusual matrices. For example, matrices with element values 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 matrix whose elements are 1's and 'ones(3,2)' creates a 3x2 matrix whose elements 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 not alter the previously defined matrix A, which is only a basis for the size of the matrix created by commands zeros() and ones(). The identity matrix is a square matrix with 1's on the diagonal and 0's off the diagonal. Thus a 4x4 identity matrix, a, is a=[1 0 0 0 0 1 0 0
http://www-psych.nmsu.edu/~jkroger/lab/Manuals/MATLAB_commands.htm Page 25 of 26

A BRIEF LIST OF MATLAB COMMANDS

1/14/10 11:00 AM

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 and eye(2,3) creates 1 0 0 0 1 0 PRACTICE 1. The first four terms of the fourier series for the square wave whose amplitude is 5 and whose period is 2 is y = (20/)[sinx + (1/3)sin3x + (1/5)sin5x + (1/7)sin7x)] 0 1 0

Calculate this series, term by term, and plot the results for each partial sum.

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

Page 26 of 26

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

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=

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

1 2 3 4 5 6 9 8 7

t=

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:

0 2 4 6 8 10 12 14 16 18 20

b=a+2

b=

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

3 4 5 6 7 8 11 10 9

c=

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)

4 6 8 10 12 14 20 18 16

ans = 0.7071

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

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 =

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]

1 3 -15 -2 9

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 =

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])

17

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];

ans = -5.5745 2.5836 -0.7951 0.7860

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

z =

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)

1 6 16 16

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 mfile, 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

xx = 1 2 R = 0 0 0 0

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 =
Matrices

1 5 10

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 5 9

2 6 10

3 7 11

4 8 12

B = [ 1 2 3 4

5 6 7 8 9 10 11 12]

B =

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'

1 5 9

2 6 10

3 7 11

4 8 12

C =

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

1 2 3 4

5 6 7 8

9 10 11 12

D = 30 70 110
D = C * B

70 110 174 278 278 446

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

D = 107 122 137 152

122 140 158 176

137 158 179 200

152 176 200 224

E =

1 3

2 4

F =

2 4

3 5

G =

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

2 6 12 20

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

ans = 37 81

54 118

You can also find the inverse of a matrix: X = inv(E)

ans = 1 27

8 64

or its eigenvalues:

X = -2.0000 1.5000

1.0000 -0.5000

eig(E)

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)

ans = -0.3723 5.3723

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

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"

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.

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 =

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

1 4 7

2 5 8

3 6 9

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

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. Recalls the last command entered. You can repeat it to go farther back, or press <DOWN ARROW> to scroll forward. Recalls the last command entered that starts with "abc".

>> <UP ARROW>

>> abc<UP ARROW>

>> more on >> more off

Turns on and off more, which displays all output (including help information) one screen at a time. Tells you what variables currently exist. Deletes all variables, or the specified variable. Displays variables (but not systems) with more digits. Does not affect storage or computation. Gets rid of the extra blank lines in the display.

>> who

>> clear >> clear variable >> format long g >> format compact

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

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. 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.

>> subplot(m,n,p)

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

Labels the axes or the entire subplot with specified text

(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. Toggles on and off a grid superimposed over the current graph; you can also type grid on and grid off.
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).

>> grid

>> sgrid

>> 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. 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,

>> zoom

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.

>> max(y)

Returns the largest element in the vector y. Returns the inverse of the square, nonsingular matrix A. Calculates the determinant of the matrix 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. Returns the rank of any matrix A.

>> inv(A)

>> det(A)

>> eig(A) >> [V,D] = eig(A)

>> rank(A)

Commands useful in system analysis: >> roots(f) Returns the roots of a polynomial, where f

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. 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

>> sys1=tf(num,den) >> sys2=ss(A,B,C,D) >> sys1=tf(sys2) >> sys2=ss(sys1)

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). 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

>> sys3=series(sys1,sys2)

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. 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

>> impulse(sys) >> step(sys)

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. Plots the behavior of the given statespace system with initial condition x0 and no input. Plots the response of the given system to the input signal u(t). The initial condition x0 can be added for state-space systems. Plots the Bode or Nyquist diagram for the given system(s). A plot is drawn if no

>> initial(sys,x0)

>> lsim(sys,u,t,x0)

>> bode(sys1,sys2,...) >> [mag.phase,w]=bode(sys,w) >> nyquist(sys)

>> {re,im,w]=nyquist(sys,w)

return arguments. The frequency points may be specified in the vector w . 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. 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.

>> margin(sys) >> [gm,pm,wcg,wcp]=margin(sys)

>> rlocus(sys,k)

>> 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. Finds a canonical form of the given system; the argument "form" can be either "modal" or "companion" (in single quotes).

>> sys2=canon(sys1,'form')

>> rltool

Opens a tool for designing controllers using the root locus plots.

S-ar putea să vă placă și