Here is a function to calculate the factorial of an integer N using a for loop:
function fact = factorial(N)
fact = 1;
for i = 1:N
fact = fact * i;
end
end
To test it:
N = 5;
result = factorial(N);
This function:
1. Initializes the factorial variable fact to 1 outside the loop
2. Uses a for loop from 1 to N to iterate over the integers
3. On each iteration, it multiplies the running fact variable by the current integer i
4. After the loop, fact will contain the final factorial
This book is intended for education and fun. Python is an amazing, text-based coding language, perfectly suited for children older than the age of 10. The Standard Python library has a module called Turtle which is a popular way to introduce programming to kids. This library enables children to create pictures and shapes by providing them with a virtual canvas. With the Python Turtle library, you can create nice animation projects using images that are taken from the internet, scaled-down stored as a gif-files download to the projects. The book includes 19 basic lessons with examples that introduce to the Python codes through Turtle library which is convenient to the school students of 10+years old. The book has also a lot of projects that show how to make different animations with Turtle graphics: games, applications to math, physics, and science.
This book is intended for education and fun. Python is an amazing, text-based coding language, perfectly suited for children older than the age of 10. The Standard Python library has a module called Turtle which is a popular way to introduce programming to kids. This library enables children to create pictures and shapes by providing them with a virtual canvas. With the Python Turtle library, you can create nice animation projects using images that are taken from the internet, scaled-down stored as a gif-files download to the projects. The book includes 19 basic lessons with examples that introduce to the Python codes through Turtle library which is convenient to the school students of 10+years old. The book has also a lot of projects that show how to make different animations with Turtle graphics: games, applications to math, physics, and science.
SVGo is a Go programming language library for generation of SVG. The talk discusses the design of the library, the concept of sketching in code, and the development of visualizations and tools.
AdRoll Tech Talk Presentation:
In this talk I present three approaches to understanding monads:
- How Monads Arise Naturally
- Monads as Implemented in Haskell
- Monads in Category Theory
Desk reference for data visualization in Stata. Co-authored with Tim Essam(@StataRGIS, linkedin.com/in/timessam). See all cheat sheets at http://bit.ly/statacheatsheets. Updated 2016/06/03
SVGo is a Go programming language library for generation of SVG. The talk discusses the design of the library, the concept of sketching in code, and the development of visualizations and tools.
AdRoll Tech Talk Presentation:
In this talk I present three approaches to understanding monads:
- How Monads Arise Naturally
- Monads as Implemented in Haskell
- Monads in Category Theory
Desk reference for data visualization in Stata. Co-authored with Tim Essam(@StataRGIS, linkedin.com/in/timessam). See all cheat sheets at http://bit.ly/statacheatsheets. Updated 2016/06/03
The name MATLAB stands for MATrix LABoratory.MATLAB is a high-performance language for technical computing.
It integrates computation, visualization, and programming environment. Furthermore, MATLAB is a modern programming language environment: it has sophisticated data structures, contains built-in editing and debugging tools, and supports object-oriented programming.
These factor make MATLAB an excellent tool for teaching and research.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
2. 6.094
Introduction to Programming in MATLAB®
Lecture 2: Visualization and Programming
Sourav Dey
Danilo Šćepanović
Ankit Patel
Patrick Ho
IAP 2009
3. Outline
(1) Plotting Continued
(2) Scripts
(3) Functions
(4) Flow Control
4. Cartesian Plots
• We have already seen the plot function
» x=-pi:pi/100:pi;
» y=cos(4*x).*sin(10*x).*exp(-abs(x));
» plot(x,y,'k-');
• The same syntax applies for semilog and loglog plots
» semilogx(x,y,'k');
50
10
» semilogy(y,'r.-'); 40
10
» loglog(x,y); 30
10
• For example:
20
10
» x=0:100; 10
10
» semilogy(x,exp(x),'k.-');
0
10
0 10 20 30 40 50 60 70 80 90 100
5. Playing with the Plot
to select lines
and delete or
change to see all plot
properties tools at once
to slide the plot
to zoom in/out around
Courtesy of The MathWorks, Inc. Used with permission.
6. Line and Marker Options
• Everything on a line can be customized
» plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
• See doc line for a full list of 0.8
properties that can be specified 0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-4 -3 -2 -1 0 1 2 3 4
7. Labels
• Last time we saw how to add titles and labels using the GUI. Can
also do it command-line:
» title('Stress-Strain');
» xlabel('Force (N)');
• For multiple lines, add a legend entry for each line
» legend('Steel','Aluminum','Tungsten');
• Can specify font and size for the text
» ylabel('Distance (m)','FontSize',14,...
'FontName','Helvetica');
use ... to break long commands across multiple lines
• To put parameter values into labels, need to use num2str and
concatenate:
» str = [‘Strength of ' num2str(d) 'cm diameter rod'];
» title(str)
8. Axis
• A grid makes it easier to read values
» grid on
• xlim sets only the x axis limits
» xlim([-pi pi]);
• ylim sets only the y axis limits
» ylim([-1 1]);
• To specify both at once, use axis:
» axis([-pi pi -1 1]);
sets the x axis limits between -pi and pi and the y axis limits
between -1 and 1
• Can specify tickmarks
» set(gca,'XTick', linspace(-pi,pi,3))
see doc axes for a list of properties you can set this way
more on advanced figure customization in lecture 4
9. Axis Modes
• Built-in axis modes
» axis square
makes the current axis look like a box
» axis tight
fits axes to data
» axis equal
makes x and y scales the same
» axis xy
puts the origin in the bottom left corner (default)
» axis ij
puts the origin in the top left corner (for viewing matrices)
10. Multiple Plots in one Figure
• Use the figure command to open a new figure
» figure
• or activate an open figure
» figure(1)
• To have multiple axes in one figure
» subplot(2,3,1) or subplot(231)
makes a figure with 2 rows and three columns of axes, and
activates the first axis for plotting
each axis can have labels, a legend, and a title
» subplot(2,3,4:6)
activating a range of axes fuses them into one
• To close existing figures
» close([1 3])
closes figures 1 and 3
» close all
closes all figures (useful in scripts/functions)
11. Copy/Paste Figures
• Figures can be pasted into other apps (word, ppt, etc)
• Edit copy options figure copy template
Change font sizes, line properties; presets for word and ppt
• Edit copy figure to copy figure
• Paste into document of interest
Courtesy of The MathWorks, Inc. Used with permission.
12. Saving Figures
• Figures can be saved in many formats. The common ones
are:
.fig preserves all
information
.bmp uncompressed
image
.eps high-quality
scaleable format
.pdf compressed
image
Courtesy of The MathWorks, Inc.
Used with permission.
13. Figures: Exercise
• Open a figure and plot a sine wave over two periods with
data points at 0, pi/8, 2pi/8… . Use black squares as
markers and a dashed red line of thickness 2 as the line
» figure
» plot(0:pi/4:4*pi,sin(0:pi/4:4*pi),'rs--',...
'LineWidth',2,'MarkerFaceColor','k');
• Save the figure as a pdf
• View with pdf viewer.
14. Visualizing matrices
• Any matrix can be visualized as an image
» mat=reshape(1:10000,100,100);
» imagesc(mat);
» colorbar
• imagesc automatically scales the values to span the entire
colormap
• Can set limits for the color axis (analogous to xlim, ylim)
» caxis([3000 7000])
15. Colormaps
• You can change the colormap:
» imagesc(mat)
default map is jet
» colormap(gray)
» colormap(cool)
» colormap(hot(256))
• See help hot for a list
• Can define custom colormap
» map=zeros(256,3);
» map(:,2)=(0:255)/255;
» colormap(map);
16. Images: Exercise
• Construct a Discrete Fourier Transform Matrix of size 128
using dftmtx
• Display the phase of this matrix as an image using a hot
colormap with 256 colors
» dMat=dftmtx(128);
» phase=angle(dMat);
» imagesc(phase);
» colormap(hot(256));
17. 3D Line Plots
• We can plot in 3 dimensions just as easily as in 2
» time=0:0.001:4*pi;
» x=sin(time);
» y=cos(time);
» z=time;
» plot3(x,y,z,'k','LineWidth',2);
» zlabel('Time');
10
• Use tools on figure to rotate it 5
• Can set limits on all 3 axes 0
-5
» xlim, ylim, zlim
-10
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1
18. Surface Plots
• It is more common to visualize surfaces in 3D
• Example: f ( x, y ) = sin ( x ) cos ( y )
x ∈ [ −π ,π ] ; y ∈ [ −π ,π ]
• surf puts vertices at specified points in space x,y,z, and
connects all the vertices to make a surface
• The vertices can be denoted by matrices X,Y,Z
• How can we make these matrices
loop (DUMB)
built-in function: meshgrid
19. surf
• Make the x and y vectors
» x=-pi:0.1:pi;
» y=-pi:0.1:pi;
• Use meshgrid to make matrices (this is the same as loop)
» [X,Y]=meshgrid(x,y);
• To get function values,
evaluate the matrices
» Z =sin(X).*cos(Y);
• Plot the surface
» surf(X,Y,Z)
» surf(x,y,Z);
20. surf Options
• See help surf for more options
• There are three types of surface shading
» shading faceted
» shading flat
» shading interp
• You can change colormaps
» colormap(gray)
21. contour
• You can make surfaces two-dimensional by using contour
» contour(X,Y,Z,'LineWidth',2)
takes same arguments as surf
color indicates height
can modify linestyle properties
can set colormap
» hold on
» mesh(X,Y,Z)
22. Exercise: 3-D Plots
• Plot exp(-.1(x^2+y^2))*sin(xy) for x,y in [–2*pi,2*pi]
with interpolated shading and a hot colormap:
» x=-2*pi:0.1:2*pi;
» y=-2*pi:0.1:2*pi;
» [X,Y]=meshgrid(x,y);
» Z =exp(-.1*(X.^2+Y.^2)).*sin(X.*Y);
» surf(X,Y,Z);
» shading interp
» colormap hot
23. Specialized Plotting Functions
• MATLAB has a lot of specialized plotting functions
• polar-to make polar plots
» polar(0:0.01:2*pi,cos((0:0.01:2*pi)*2))
• bar-to make bar graphs
» bar(1:10,rand(1,10));
• quiver-to add velocity vectors to a plot
» [X,Y]=meshgrid(1:10,1:10);
» quiver(X,Y,rand(10),rand(10));
• stairs-plot piecewise constant functions
» stairs(1:10,rand(1,10));
• fill-draws and fills a polygon with specified vertices
» fill([0 1 0.5],[0 0 1],'r');
• see help on these functions for syntax
• doc specgraph – for a complete list
24. Outline
(1) Plotting Continued
(2) Scripts
(3) Functions
(4) Flow Control
25. Scripts: Overview
• Scripts are
written in the MATLAB editor
saved as MATLAB files (.m extension)
evaluated line by line
• To create an MATLAB file from command-line
» edit myScript.m
• or click
Courtesy of The MathWorks, Inc. Used with permission.
26. Scripts: the Editor
* Means that it's not saved
Line numbers
MATLAB
file path Debugging tools
Help file
Comments
Courtesy of The MathWorks, Inc. Used with permission.
Possible breakpoints
27. Scripts: Good Practice
• Take advantage of "smart indent" option
• Keep code clean
Use built-in functions
Vectorize, vectorize, vectorize
When making large matrices, allocate space first
– Use nan or zeros to make a matrix of the desired size
• Keep constants at the top of the MATLAB file
• COMMENT!
Anything following a % is seen as a comment
The first contiguous comment becomes the script's help file
Comment thoroughly to avoid wasting time later
28. Hello World
• Here are several flavors of Hello World to introduce MATLAB
• MATLAB will display strings automatically
» ‘Hello 6.094’
• To remove “ans =“, use disp()
» disp('Hello 6.094')
• sprintf() allows you to mix strings with variables
» class=6.094;
» disp(sprintf('Hello %g', class))
The format is C-syntax
29. Exercise: Scripts
• A student has taken three exams. The performance on the
exams is random (uniform between 0 and 100)
• The first exam is worth 20%, the second is worth 30%, and
the final is worth 50% of the grade
• Calculate the student's overall score
• Save script as practiceScript.m and run a few times
» scores=rand(1,3)*100;
» weights=[0.2 0.3 0.5];
» overall=scores*weights’
30. Outline
(1) Plotting Continued
(2) Scripts
(3) Functions
(4) Flow Control
31. User-defined Functions
• Functions look exactly like scripts, but for ONE difference
Functions must have a function declaration
Help file
Function declaration
Outputs Inputs
Courtesy of The MathWorks, Inc. Used with permission.
32. User-defined Functions
• Some comments about the function declaration
Inputs must be specified
function [x, y, z] = funName(in1, in2)
Must have the reserved Function name should
word: function match MATLAB file
name
If more than one output,
must be in brackets
• No need for return: MATLAB returns the variables whose
names match those in the function declaration
• Variable scope: Any variables created within the function
but not returned disappear after the function stops running
• Can have variable input arguments (see help varargin)
33. Functions: Exercise
• Take the script we wrote to calculate the student's overall
score and make it into a function
• The inputs should be
the scores row vector
the weight row vector, with the same length as scores
• The output should be
A scalar: the overall score
• Assume the user knows the input constraints (no need to
check if the inputs are in the correct formatsize)
• Name the function overallScore.m
35. Functions
• We're familiar with
» zeros
» size
» length
» sum
• Look at the help file for size by typing
» help size
• The help file describes several ways to invoke the function
D = SIZE(X)
[M,N] = SIZE(X)
[M1,M2,M3,...,MN] = SIZE(X)
M = SIZE(X,DIM)
36. Functions
• MATLAB functions are generally overloaded
Can take a variable number of inputs
Can return a variable number of outputs
• What would the following commands return:
» a=zeros(2,4,8);
» D=size(a)
» [m,n]=size(a)
» [x,y,z]=size(a)
» m2=size(a,2)
• Take advantage of overloaded methods to make your code
cleaner!
37. Outline
(1) Plotting Continued
(2) Scripts
(3) Functions
(4) Flow Control
38. Relational Operators
• MATLAB uses mostly standard relational operators
equal ==
not equal ~=
greater than >
less than <
greater or equal >=
less or equal <=
• Logical operators normal bitwise
And & &&
Or | ||
Not ~
Xor xor
All true all
Any true any
• Boolean values: zero is false, nonzero is true
• See help . for a detailed list of operators
39. if/else/elseif
• Basic flow-control, common to all languages
• MATLAB syntax is somewhat unique
IF ELSE ELSEIF
if cond if cond if cond1
commands commands1 commands1
end else elseif cond2
commands2 commands2
end else
Conditional statement:
evaluates to true or false commands3
end
• No need for parentheses: command blocks are between
reserved words
40. for
• for loops: use for a definite number of iterations
• MATLAB syntax:
Loop variable
for n=1:100
commands
end Command block
• The loop variable
Is defined as a vector
Is a scalar within the command block
Does not have to have consecutive values
• The command block
Anything between the for line and the end
41. while
• The while is like a more general for loop:
Don't need to know number of iterations
WHILE
while cond
commands
end
• The command block will execute while the conditional
expression is true
• Beware of infinite loops!
42. Exercise: Control-Flow
• Write a function to calculate the factorial of an integer N using a
loop (you can use a for or while loop). If the input is less than 0,
return NaN. Test it using some values.
» function a = factorial(N)
» if N<0,
» a=nan,
» else
» a = 1;
» for k=1:N
» a = a*k;
» end
» end
• But note that factorial() is already implemented! You should see if
there are built-in functions before implementing something
yourself.
» which factorial
43. find
• find is a very important function
Returns indices of nonzero values
Can simplify code and help avoid loops
• Basic syntax: index=find(cond)
» x=rand(1,100);
» inds = find(x>0.4 & x<0.6);
• inds will contain the indices at which x has values between
0.4 and 0.6. This is what happens:
x>0.4 returns a vector with 1 where true and 0 where false
x<0.6 returns a similar vector
The & combines the two vectors using an and
The find returns the indices of the 1's
44. Exercise: Flow Control
• Given x= sin(linspace(0,10*pi,100)), how many of the
entries are positive?
Using a loop and if/else Being more clever
count=0; count=length(find(x>0));
for n=1:length(x)
length(x) Loop time Find time
if x(n)>0
100 0.01 0
count=count+1;
10,000 0.1 0
end
100,000 0.22 0
end
1,000,000 1.5 0.04
• Avoid loops like the plague!
• Built-in functions will make it faster to write and execute
45. Efficient Code
• Avoid loops whenever possible
This is referred to as vectorization
• Vectorized code is more efficient for MATLAB
• Use indexing and matrix operations to avoid loops
• For example:
» a=rand(1,100); » a=rand(1,100);
» b=zeros(1,100); » b=[0 a(1:end-1)]+a;
» for n=1:100 Efficient and clean
» if n==1
» b(n)=a(n);
» else
» b(n)=a(n-1)+a(n);
» end
» end
Slow and complicated
46. Exercise: Vectorization
• Alter your factorial program to work WITHOUT a loop. Use
prod
» function a=factorial(N)
» a=prod(1:N);
• You can tic/toc to see how much faster this is than the
loop!
• BUT…Don’t ALWAYS avoid loops
Over-vectorizing code can obfuscate it, i.e. you won’t be
able to understand or debug it later
Sometime a loop is the right thing to do, it is clearer and
simple
47. End of Lecture 2
(1) Plotting Continued
(2) Scripts
(3) Functions
(4) Flow Control
Vectorization makes
coding fun!