SlideShare a Scribd company logo
1 of 18
Piecewise Functions
In Scilab
Piecewise Functions
• A piecewise function is a function which is
defined by multiple sub functions, each
sub function applying to a certain interval
of the main function's domain.
Piecewise Functions
• I’ll show you two ways to define and plot
them in Scilab:
1. With iterations, one element at a time.
2. Without iterations, the vectorized way.
(I’m using Scilab ver 5.4.0 for Win 7 - 64 bits)
Piecewise Functions
1.- Using Iterations
• First, you are going to define your piecewise
function, where you’ll consider a scalar number
as input. You’ll verify each interval and assign the
appropriate value.
• Second, you’ll call that function for all the
necessary elements.
• At the end, you’ll have two vectors, x and y, so
that you can plot your initial function.
1.- Using Iterations – Define PW
// Define your function assuming that you'll
// get a scalar as input
function y = pw1(x)
// Filter and evaluate your first interval
if x <= 1 then y = -x/3 + 4/3;
// Filter and evaluate your second interval
elseif (1 < x) & (x <= 3) then y = x^2/6 + x/3 + .5;
// Filter and define your remaining intervals
else y = .5*x + 1.5;
end
endfunction
1.- Using Iterations – Call Function
// Clear your command window and clear memory
clc, clear
// Make sure that Scilab can see your function.
// Load it into memory and add the full path if necessary
exec('C:UsersUsuarioDocumentsScilab_docspw1.sci');
// This is your range of interest
x = -2 : .2 : 5;
// Call the function and evaluate element-by-element
for ix = 1 : length(x)
y(ix) = pw1(x(ix));
end
// Now you have your vectors ready to plot
1.- Using Iterations – Call Function
// Plot and add labels if needed
plot(x, y, 'ro-')
title('Piecewise in Scilab - Example 1');
xlabel('x');
ylabel('y');
2.- Using Vectorization
• First, you are going to define your piecewise
function, where you’ll consider a vector as input.
You’ll find values for each interval and assign the
appropriate values.
• Second, you’ll call that function as you would for
any other function that takes vectors.
• At the end, you’ll have two arrays, x and y, so that
you can plot the function under study.
2.- Using Vectorization
x = -2 : .2 : 5;
y = pw2(x);
plot(x, y)
Ideally, you should type something like this
and get the same plot shown above
interval of interest
function to be defined
call the plot, just as it’s done
with any other function
2.- Using Vectorization
The interesting part is how to define the
piecewise function without going element-by-
element in the domain, but going instead
interval-by-interval.
To accomplish this, we’ll use two ideas:
• Specially selected indices.
• Function find.
2.- Using Vectorization
In Scilab, if we have vector x = [-2 -1 0 1 2 3 4 5 6 7 8 9], and do this:
i2 = x(0 < x & x <= 3)
we’ll take all the values in vector x that meet the condition 0 < x ≤ 3, that is,
i2 = [1 2 3]
If we do:
i3 = x(3 < x & x <= 8)
we’ll take all the values in vector x that meet the condition 3 < x ≤ 8, thus
i3 = [4 5 6 7 8]
First important concept: special indices
2.- Using Vectorization
In Scilab, if we have vector x = [-2 -1 0 1 2 3 4 5 6 7 8 9], and do this:
find(0 < x & x <= 3)
we’ll find the indices (not values) in vector x that meet 0 < x ≤ 3, so we’ll get
the vector [4 5 6].
If we do:
find(3 < x & x <= 8)
we’ll get the vector [7 8 9 10 11]
Second important concept: function find
2.- Using Vectorization – Define PW
Putting all together, defining the function under study:
// Define your function considering a vector as an input
function y = pw2(x)
// Find the indices for the first interval
ix1 = find(x <= 1);
// Assign the appropriate values to the correct values
y(ix1) = -x(ix1)/3 + 4/3;
// Now the second interval, repeat the concept
ix2 = find(1 < x & x <= 3);
y(ix2) = x(ix2).^2/6 + x(ix2)/3 + .5;
2.- Using Vectorization – Define PW
// Now, the last interval for this function
ix3 = find(x > 3);
y(ix3) = .5*x(ix3) + 1.5;
endfunction
2.- Using Vectorization– Call Function
// Clear your command window and clear memory
clc, clear
// Make sure that Scilab can see your function.
// Load it into memory and add the full path if necessary
exec('C:UsersUsuarioDocumentsScilab_docspw2.sci');
// This is your range of interest
x = -2 : .2 : 5;
// Call the function - don’t need iterations
y = pw2(x);
// Now you have your vectors ready to plot
2.- Using Vectorization– Call Function
// Plot and add labels if needed
plot(x, y, 'bo-')
title('Piecewise in Scilab - Example 2');
xlabel('x');
ylabel('f(x)');
For more examples and details, visit:
matrixlab-examples.com/scilab-piecewise-function.html

More Related Content

What's hot

Inverse trig functions
Inverse trig functionsInverse trig functions
Inverse trig functionsJessica Garcia
 
Linear Functions Presentation
Linear Functions PresentationLinear Functions Presentation
Linear Functions PresentationMelanie Loslo
 
Domain and range of a RELATION
Domain and range of a RELATIONDomain and range of a RELATION
Domain and range of a RELATIONJanak Singh saud
 
Relations and functions
Relations and functionsRelations and functions
Relations and functionscannout
 
Vector space - subspace By Jatin Dhola
Vector space - subspace By Jatin DholaVector space - subspace By Jatin Dhola
Vector space - subspace By Jatin DholaJatin Dhola
 
Piecewise Functions in Matlab
Piecewise Functions in MatlabPiecewise Functions in Matlab
Piecewise Functions in MatlabJorge Jasso
 
Lesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic FunctionsLesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic FunctionsMatthew Leingang
 
Parabola
ParabolaParabola
Parabolaitutor
 
Calculus of variations
Calculus of variationsCalculus of variations
Calculus of variationsSolo Hermelin
 
Lecture 5 inverse of matrices - section 2-2 and 2-3
Lecture 5   inverse of matrices - section 2-2 and 2-3Lecture 5   inverse of matrices - section 2-2 and 2-3
Lecture 5 inverse of matrices - section 2-2 and 2-3njit-ronbrown
 
Lecture artificial neural networks and pattern recognition
Lecture   artificial neural networks and pattern recognitionLecture   artificial neural networks and pattern recognition
Lecture artificial neural networks and pattern recognitionHưng Đặng
 
Lagrange's equation with one application
Lagrange's equation with one applicationLagrange's equation with one application
Lagrange's equation with one applicationZakaria Hossain
 
24 double integral over polar coordinate
24 double integral over polar coordinate24 double integral over polar coordinate
24 double integral over polar coordinatemath267
 
Complex Numbers
Complex NumbersComplex Numbers
Complex Numbersswartzje
 
Linear functions
Linear functionsLinear functions
Linear functionshalcr1ja
 

What's hot (20)

Math1.4
Math1.4Math1.4
Math1.4
 
Inverse trig functions
Inverse trig functionsInverse trig functions
Inverse trig functions
 
Linear Functions Presentation
Linear Functions PresentationLinear Functions Presentation
Linear Functions Presentation
 
Domain and range of a RELATION
Domain and range of a RELATIONDomain and range of a RELATION
Domain and range of a RELATION
 
QUADRATIC FUNCTIONS
QUADRATIC FUNCTIONSQUADRATIC FUNCTIONS
QUADRATIC FUNCTIONS
 
Relations and functions
Relations and functionsRelations and functions
Relations and functions
 
Math12 lesson11
Math12 lesson11Math12 lesson11
Math12 lesson11
 
Vector space - subspace By Jatin Dhola
Vector space - subspace By Jatin DholaVector space - subspace By Jatin Dhola
Vector space - subspace By Jatin Dhola
 
Piecewise Functions in Matlab
Piecewise Functions in MatlabPiecewise Functions in Matlab
Piecewise Functions in Matlab
 
Intro to Logs
Intro to LogsIntro to Logs
Intro to Logs
 
Lesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic FunctionsLesson 16: Derivatives of Exponential and Logarithmic Functions
Lesson 16: Derivatives of Exponential and Logarithmic Functions
 
Parabola
ParabolaParabola
Parabola
 
Calculus of variations
Calculus of variationsCalculus of variations
Calculus of variations
 
Lecture 5 inverse of matrices - section 2-2 and 2-3
Lecture 5   inverse of matrices - section 2-2 and 2-3Lecture 5   inverse of matrices - section 2-2 and 2-3
Lecture 5 inverse of matrices - section 2-2 and 2-3
 
Lecture artificial neural networks and pattern recognition
Lecture   artificial neural networks and pattern recognitionLecture   artificial neural networks and pattern recognition
Lecture artificial neural networks and pattern recognition
 
Lagrange's equation with one application
Lagrange's equation with one applicationLagrange's equation with one application
Lagrange's equation with one application
 
Rational numbers
Rational numbersRational numbers
Rational numbers
 
24 double integral over polar coordinate
24 double integral over polar coordinate24 double integral over polar coordinate
24 double integral over polar coordinate
 
Complex Numbers
Complex NumbersComplex Numbers
Complex Numbers
 
Linear functions
Linear functionsLinear functions
Linear functions
 

Similar to Scilab - Piecewise Functions

Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxjkapardhi
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
C++ and Data Structure.ppt
C++ and Data Structure.pptC++ and Data Structure.ppt
C++ and Data Structure.pptRich Alex
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete Adnan abid
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Megha V
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptximman gwu
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Philip Schwarz
 

Similar to Scilab - Piecewise Functions (20)

Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptx
 
2D Plot Matlab
2D Plot Matlab2D Plot Matlab
2D Plot Matlab
 
FUNDAMETAL ALG.ppt
FUNDAMETAL ALG.pptFUNDAMETAL ALG.ppt
FUNDAMETAL ALG.ppt
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
C++ and Data Structure.ppt
C++ and Data Structure.pptC++ and Data Structure.ppt
C++ and Data Structure.ppt
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Ch6
Ch6Ch6
Ch6
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 
COMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptxCOMPANION TO MATRICES SESSION II.pptx
COMPANION TO MATRICES SESSION II.pptx
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
 

Recently uploaded

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Scilab - Piecewise Functions

  • 2. Piecewise Functions • A piecewise function is a function which is defined by multiple sub functions, each sub function applying to a certain interval of the main function's domain.
  • 3. Piecewise Functions • I’ll show you two ways to define and plot them in Scilab: 1. With iterations, one element at a time. 2. Without iterations, the vectorized way. (I’m using Scilab ver 5.4.0 for Win 7 - 64 bits)
  • 5. 1.- Using Iterations • First, you are going to define your piecewise function, where you’ll consider a scalar number as input. You’ll verify each interval and assign the appropriate value. • Second, you’ll call that function for all the necessary elements. • At the end, you’ll have two vectors, x and y, so that you can plot your initial function.
  • 6. 1.- Using Iterations – Define PW // Define your function assuming that you'll // get a scalar as input function y = pw1(x) // Filter and evaluate your first interval if x <= 1 then y = -x/3 + 4/3; // Filter and evaluate your second interval elseif (1 < x) & (x <= 3) then y = x^2/6 + x/3 + .5; // Filter and define your remaining intervals else y = .5*x + 1.5; end endfunction
  • 7. 1.- Using Iterations – Call Function // Clear your command window and clear memory clc, clear // Make sure that Scilab can see your function. // Load it into memory and add the full path if necessary exec('C:UsersUsuarioDocumentsScilab_docspw1.sci'); // This is your range of interest x = -2 : .2 : 5; // Call the function and evaluate element-by-element for ix = 1 : length(x) y(ix) = pw1(x(ix)); end // Now you have your vectors ready to plot
  • 8. 1.- Using Iterations – Call Function // Plot and add labels if needed plot(x, y, 'ro-') title('Piecewise in Scilab - Example 1'); xlabel('x'); ylabel('y');
  • 9. 2.- Using Vectorization • First, you are going to define your piecewise function, where you’ll consider a vector as input. You’ll find values for each interval and assign the appropriate values. • Second, you’ll call that function as you would for any other function that takes vectors. • At the end, you’ll have two arrays, x and y, so that you can plot the function under study.
  • 10. 2.- Using Vectorization x = -2 : .2 : 5; y = pw2(x); plot(x, y) Ideally, you should type something like this and get the same plot shown above interval of interest function to be defined call the plot, just as it’s done with any other function
  • 11. 2.- Using Vectorization The interesting part is how to define the piecewise function without going element-by- element in the domain, but going instead interval-by-interval. To accomplish this, we’ll use two ideas: • Specially selected indices. • Function find.
  • 12. 2.- Using Vectorization In Scilab, if we have vector x = [-2 -1 0 1 2 3 4 5 6 7 8 9], and do this: i2 = x(0 < x & x <= 3) we’ll take all the values in vector x that meet the condition 0 < x ≤ 3, that is, i2 = [1 2 3] If we do: i3 = x(3 < x & x <= 8) we’ll take all the values in vector x that meet the condition 3 < x ≤ 8, thus i3 = [4 5 6 7 8] First important concept: special indices
  • 13. 2.- Using Vectorization In Scilab, if we have vector x = [-2 -1 0 1 2 3 4 5 6 7 8 9], and do this: find(0 < x & x <= 3) we’ll find the indices (not values) in vector x that meet 0 < x ≤ 3, so we’ll get the vector [4 5 6]. If we do: find(3 < x & x <= 8) we’ll get the vector [7 8 9 10 11] Second important concept: function find
  • 14. 2.- Using Vectorization – Define PW Putting all together, defining the function under study: // Define your function considering a vector as an input function y = pw2(x) // Find the indices for the first interval ix1 = find(x <= 1); // Assign the appropriate values to the correct values y(ix1) = -x(ix1)/3 + 4/3; // Now the second interval, repeat the concept ix2 = find(1 < x & x <= 3); y(ix2) = x(ix2).^2/6 + x(ix2)/3 + .5;
  • 15. 2.- Using Vectorization – Define PW // Now, the last interval for this function ix3 = find(x > 3); y(ix3) = .5*x(ix3) + 1.5; endfunction
  • 16. 2.- Using Vectorization– Call Function // Clear your command window and clear memory clc, clear // Make sure that Scilab can see your function. // Load it into memory and add the full path if necessary exec('C:UsersUsuarioDocumentsScilab_docspw2.sci'); // This is your range of interest x = -2 : .2 : 5; // Call the function - don’t need iterations y = pw2(x); // Now you have your vectors ready to plot
  • 17. 2.- Using Vectorization– Call Function // Plot and add labels if needed plot(x, y, 'bo-') title('Piecewise in Scilab - Example 2'); xlabel('x'); ylabel('f(x)');
  • 18. For more examples and details, visit: matrixlab-examples.com/scilab-piecewise-function.html