This document provides a summary of MATLAB commands and their equivalents in numerical Python (NumPy) and R. It covers topics such as help, operators, vectors, matrices, random number generation and more. The goal is to provide a quick reference for switching between MATLAB, Python, Scilab, Octave, Gnuplot and R for numeric processing and data visualization. Equivalents are given for each MATLAB command or function in the other languages.
A Gentle Introduction to Coding ... with PythonTariq Rashid
A gentle introduction to coding (programming) for complete beginners. Starting from then basics - electrical wires - proceeding through variables, data structures, loops, functions, and exploring libraries for visualisation and specialist tools. Finally we use flask to make a very simple twitter clone web application.
This document describes a project to parallelize the GNU grep utility using a parallel string matching algorithm. It discusses implementing a parallel version of fgrep that uses Uzi Vishkin's parallel string matching algorithm. The implementation details and experimental results showing speedups on large files with up to 32 threads are provided. However, the parallel grep is not yet optimized enough to outperform or replace the sequential GNU grep for all use cases.
The document provides information about getting help with algorithm assignments. It lists a website, email address, and phone number that can be used for support regarding algorithm homework help.
.Net 4.0 Threading and Parallel ProgrammingAlex Moore
This document discusses parallel programming in .NET 4.0. It notes that processor speeds have stopped increasing significantly and cores are increasing instead. It introduces parallel programming concepts in .NET 4.0 like PLINQ for declarative data parallelism, Parallel.For for imperative data parallelism, and tasks for splitting computations. It also discusses concurrent collections and provides examples of using PLINQ, Parallel.For, tasks, and continuations for parallel programming.
Igor Rivin wrote about his experience learning Julia by implementing algorithms to compute multiplicative functions over integer ranges. His initial implementations in Julia were slow, taking 10 minutes to run. After profiling, he realized Julia is not a functional programming language and rewrote the algorithms to avoid excessive object creation/destruction, achieving a 1500x speedup. The key insight was to first sieve and factor all numbers, then compute functions on the prime powers, avoiding re-factoring. This approach was much faster, beating Mathematica by factorizing once and reusing factors. Rivin concluded Julia freed him from the constraints of shell languages like Mathematica while avoiding low-level languages, and reinforced the importance of keeping algorithms simple.
/
p
This document provides an overview of the CS-2251 DESIGN AND ANALYSIS OF ALGORITHMS course. It defines algorithms and discusses algorithm design and analysis processes. It covers different algorithm efficiency measures, specification methods, important problem types, classification techniques, and examples like the Euclid algorithm. Key aspects of sorting, searching, graph, combinatorial, and numerical problems are outlined. The features of efficient algorithms and orders of algorithms are defined.
tt
h
Slides from Phil Pennington\'s talk on Using Parallel Computing with Visual Studio 2010 and .NET 4.0, originally presented at the North Houston .NET Users Group (facebook.com/nhdnug).
The document summarizes and provides code examples for four pattern matching algorithms:
1. The brute force algorithm checks each character position in the text to see if the pattern starts there, running in O(mn) time in worst case.
2. The Boyer-Moore algorithm uses a "bad character" shift and "good suffix" shift to skip over non-matching characters in the text, running faster than brute force.
3. The Knuth-Morris-Pratt algorithm uses a failure function to determine the maximum shift of the pattern on a mismatch, avoiding wasteful comparisons.
4. The failure function allows KMP to skip portions of the text like Boyer-Moore, running
The document describes algorithms for text searching and pattern matching. It presents several algorithms for tasks like simple text search, Rabin-Karp search, Knuth-Morris-Pratt search, Boyer-Moore search, edit distance, approximate matching, don't-care search, and epsilon-NFA matching using pattern trees. The algorithms are explained through pseudocode with input/output parameters and complexity analysis provided for some.
This document provides an introduction to the Python programming language. It describes Python as a multi-purpose, object-oriented language that is interpreted, dynamically typed and focuses on readability. It lists several major organizations that use Python. It then provides examples of basic Python programs and covers key Python concepts like variables, data types, strings, comments, functions and more in under 3 sentences each.
The document provides an introduction to the Python programming language. It discusses what Python is, its creator Guido van Rossum, and how to write a simple "Hello World" program. It also covers Python data types, operators, flow control using conditionals and loops, functions, input/output operations, and the Zen of Python philosophy guiding Python's design. The document serves as the first day of instruction in a Python course.
Basic Computer Engineering Unit II as per RGPV SyllabusNANDINI SHARMA
The document provides an overview of algorithms and computational complexity. It defines an algorithm as a set of unambiguous steps to solve a problem, and discusses how algorithms can be expressed using different languages. It then covers algorithmic complexity and how to analyze the time complexity of algorithms using asymptotic notation like Big-O notation. Specific time complexities like constant, linear, logarithmic, and quadratic time are defined. The document also discusses flowcharts as a way to represent algorithms graphically and introduces some basic programming concepts.
Tensorflow in practice by Engineer - donghwi chaDonghwi Cha
- Tensorflow is an introduction to the machine learning framework Tensorflow covering key concepts like computation graphs, operations, sessions, training, replication, and clustering.
- Key aspects discussed include how Tensorflow executes operations as a static computation graph, uses sessions to run graphs and tensors to hold values, and supports data parallelism through replication across devices/workers.
- The document provides examples of building neural network models in Tensorflow and discusses techniques for training models like backpropagation and distributing training using data parallelism.
SciPy and NumPy are Python packages that provide scientific computing capabilities. NumPy provides multidimensional array objects and fast linear algebra functions. SciPy builds on NumPy and adds modules for optimization, integration, signal and image processing, and more. Together, NumPy and SciPy give Python powerful data analysis and visualization capabilities. The community contributes to both projects to expand their functionality. Memory mapped arrays in NumPy allow working with large datasets that exceed system memory.
Python for Scientific Computing -- Ricardo Cruzrpmcruz
This document discusses Python for scientific computing. It provides notes on NumPy, the fundamental package for scientific computing in Python. NumPy allows vectorized mathematical operations on multidimensional arrays in a simple and efficient manner. The notes cover common NumPy operations and syntax as compared to MATLAB and R. Pandas is also introduced as a package for data manipulation and analysis based on the concept of data frames from R. Examples are given of generating fake data to demonstrate modeling capabilities in Python.
This document provides a tutorial on using the argparse module in Python to parse command line arguments. It begins with simple examples of defining positional and optional arguments, and progresses to combining the two and adding more advanced features like different argument types and actions. The goal is to introduce argparse concepts gradually through examples, building up an understanding of how to define, accept, and handle different types of arguments from the command line.
(Slides) Task scheduling algorithm for multicore processor system for minimiz...Naoki Shibata
Shohei Gotoda, Naoki Shibata and Minoru Ito : "Task scheduling algorithm for multicore processor system for minimizing recovery time in case of single node fault," Proceedings of IEEE International Symposium on Cluster Computing and the Grid (CCGrid 2012), pp.260-267, DOI:10.1109/CCGrid.2012.23, May 15, 2012.
In this paper, we propose a task scheduling al-gorithm for a multicore processor system which reduces the
recovery time in case of a single fail-stop failure of a multicore
processor. Many of the recently developed processors have
multiple cores on a single die, so that one failure of a computing
node results in failure of many processors. In the case of a failure
of a multicore processor, all tasks which have been executed
on the failed multicore processor have to be recovered at once.
The proposed algorithm is based on an existing checkpointing
technique, and we assume that the state is saved when nodes
send results to the next node. If a series of computations that
depends on former results is executed on a single die, we need
to execute all parts of the series of computations again in
the case of failure of the processor. The proposed scheduling
algorithm tries not to concentrate tasks to processors on a die.
We designed our algorithm as a parallel algorithm that achieves
O(n) speedup where n is the number of processors. We evaluated
our method using simulations and experiments with four PCs.
We compared our method with existing scheduling method, and
in the simulation, the execution time including recovery time in
the case of a node failure is reduced by up to 50% while the
overhead in the case of no failure was a few percent in typical
scenarios.
This document discusses scheduling disciplines for computer networks. It outlines that scheduling is needed to resolve contention when resources are shared and to fairly allocate bandwidth, delay, and loss. The key requirements for an ideal scheduling discipline are that it is easy to implement, fair, provides performance bounds, and allows for easy admission control decisions. There are several fundamental choices in designing a scheduling discipline, such as the number of priority levels, whether it is work-conserving or non-work-conserving, the degree of aggregation, and the service order within each level. Non-work-conserving disciplines can reduce delay-jitter but may waste bandwidth and always punish misbehaving sources.
Virtual time round-robin scheduler presented by Parang Saraf (CS4204 VT)Parang Saraf
Presentation on the paper: "Virtual time round-robin O(1) proportional share scheduler"
If you need a copy of this presentation, feel free to msg me at parang[DOT]saraf[AT]gmail
The document discusses different types of scheduling algorithms. It describes cyclic scheduling, where a set of periodic tasks are executed repeatedly in a defined cycle. Round robin scheduling is also covered, where each task gets a time slice to execute in a cyclic queue before the next task runs. The round robin algorithm aims to be fair by giving each task an equal share of CPU time. Examples of using these algorithms for orchestra robots and VoIP are provided.
Ramification of games_round robin_by Lester B. Panemlgabp
In a round robin tournament, the number of teams determines whether there will be a bye in each round or not. An even number of teams means no bye, while an odd number of teams means one bye per round. The number of games is calculated using the formula N(N-1)/2, where N is the number of teams. The document then provides examples of how 5, 6, 7, 8, 9, and 10 team tournaments would be structured over multiple rounds based on this formula.
Multiuser MIMO-OFDM simulation framework in MatlabPavel Loskot
Simulation framework for multiuser MIMO-OFDM over multipath fading channels. Also created a C-like pre-processor in Matlab to add flexibility in configuring the simulation prior its run.
The document discusses modeling a 4G LTE system in MATLAB. It provides an overview of 4G LTE standards and features, and presents a case study of modeling the downlink physical layer of an LTE system in MATLAB. Key aspects covered include channel coding, OFDM, MIMO, link adaptation, and options for simulation acceleration and connecting system design to implementation through code generation.
This document describes a script that simulates bit error rate (BER) performance for BPSK modulation over a Rayleigh fading channel with a 2 transmitter and 2 receiver (2x2) multiple-input multiple-output (MIMO) system using zero forcing equalization. The script generates transmitted bits, applies BPSK modulation, sends the signals over a Rayleigh fading channel with additive noise, uses zero forcing equalization at the receiver, and compares the estimated and transmitted bits to calculate the simulated BER over a range of signal-to-noise ratio (SNR) values. The simulated results are then plotted along with theoretical BER curves for 1x1 and 2x2 MIMO systems.
The document discusses intramural sports being held within the school and provides a schedule of games. It then explains the single elimination tournament system, providing a formula to calculate the number of games and byes based on the number of entries. It also provides an example of drawing out a single elimination bracket for a table tennis tournament with 6 teams.
In a communications system, the channel is affected by an additive white Gaussian noise (AWGN)
and a fading due to a distance between a transmitter and a receiver. Especially, there are many kinds of
channel fadings. Depending on the moving speeds of transmitters or receivers, a fading type can be a slow
fading or a fast fading (i.e., the product of 0.1 and coherence time than smaller or larger than the symbol
period of signal are corresponding to fast and slow fadings). Moreover, a channel can be referred as a
selective fading or a flat fading corresponding to the product of 0.1 and coherence bandwidth than smaller
or larger than the bandwidth of signal. These above effects can suffer received signals at a destination.
Hence the performance of received signals in term of bit-error-rate (BER) is much degraded.
In order to overcome these issues, communications systems would be carefully designed. In detail,
application systems operating over the AWGN channels would use coding schemes to combat an additive
white noise. However, if environment is affected by fading, coding techniques only solve a fast fading.
It implies that, coding schemes degrade received signals when they go through slow fading channels. In
this case, an interleaving technique would be added to a communications system. In order to overcome
the fading channels, besides, using an interleaver as above, we can exploit the diversity of multi-path. It
implies that the effects of fading can be combated by transmitting the original signals over multiple paths
(experiencing independent fading) and then combining all received signals at the receiver. There are many
kinds of diversities to mitigate this issue, such as diversity in time, frequency, and space. Correspondingly,
a lot of state-of-art methods are given, viz. diversity receiving and transmitting, OFDM, space-time block
codes, MIMO, Cooperation and etc.
In summary, the main scope of this report is modeling a communications system. First, I create a
basic communications system, where it includes the modulation/demodulation using a QPSK modulation,
a channel type is an AWGN channel. Secondly, a coder/decoder scheme is added to a transmitter/receiver to
improve received signals. Thirdly, the fading channel is considered when a receiver/transmitter is moving.
It means that the slow fading is mentioned. The performance is shown to prove that the received signal
2
is degraded whether a coding scheme is used or not. Finally, an interleaver/deinterleaver is used to solve
this problem.
Besides, the performance in terms of BER is used to verify a validity of these above techniques in a
communications system.
This document discusses modeling wireless communication systems using MATLAB. It covers:
- Characterizing the wireless channel from physics of propagation to multi-path fading channels.
- Statistical characterization of channels including Doppler spectrum, delay spread, coherence time and bandwidth.
- Simulating multi-path fading channels in MATLAB and modeling path loss.
- Explaining how multi-path propagation leads to signal distortion and is equivalent to undesired filtering.
This document provides a reference for translating MATLAB commands to equivalent commands in numerical Python (NumPy) and R. It includes sections on basic operations, vectors, matrices, random number generation, and other numerical computing tasks. The document contains over 50 MATLAB commands and their corresponding Python and R equivalents to assist users in switching from MATLAB to open-source environments like Python, Scilab, Octave, Gnuplot, or R for numeric processing and data visualization. It also provides references for further information.
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
This document provides an overview of numeric data types and operations in Python. It discusses integers and floats, and how they represent numeric values differently. Functions for determining data types like type() and converting between types are presented. Core numeric operations like addition, subtraction, multiplication, division, and modulo are covered. The use of accumulators and loops to calculate factorial and solve other numeric problems is demonstrated. Finally, the math library module is introduced for accessing advanced math functions like square root, trigonometric functions, rounding, and random number generation.
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
This document provides an overview of numeric data types and operations in Python. It discusses integers and floats, and how they represent numeric values differently. Functions for determining data types like type() and converting between types are presented. Core numeric operations like addition, subtraction, multiplication, division, and modulus are covered. The use of accumulators and loops to calculate factorial and solve other numeric problems is demonstrated. Finally, the math library module is introduced for accessing advanced math functions like square root, trigonometric functions, rounding, and random number generation.
The document discusses real-time big data management and Apache Flink. It provides an overview of Apache Flink, including its architecture, components, and APIs for batch and streaming data processing. It also provides examples of word count programs in Java, Scala, and Java 8 that demonstrate how to write Flink programs for batch and streaming data.
This document provides an introduction to MATLAB. It discusses that MATLAB is a high-performance language for technical computing that integrates computation, visualization, and programming. It can be used for tasks like math and computation, algorithm development, modeling, simulation, prototyping, data analysis, and scientific graphics. MATLAB uses arrays as its basic data type and allows matrix and vector problems to be solved more quickly than with other languages. The document then provides examples of entering matrices, using basic MATLAB commands and functions, plotting graphs, and writing MATLAB code in M-files.
1. MATLAB is a software package for mathematical computation, numerical computation, algorithm development, data analysis, and more. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages.
2. The document introduces basic MATLAB operations like arithmetic operations, variables, matrices, plotting, scripts and functions. It also discusses flow control and logical operations like if/else statements and loops.
3. MATLAB can be used for scientific and engineering applications like modeling, simulation, and prototyping through its implementation of algorithms, data analysis tools, and graphical capabilities for visualizing data.
MATLAB is a numerical computing environment and programming language. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, and interfacing with programs in other languages. MATLAB can be used for applications like signal processing, image processing, control systems, and computational finance. It offers advantages like ease of use, platform independence, and predefined functions. However, it can sometimes be slow and is commercial software. The MATLAB interface includes a command window, current directory, workspace, and command history. Arrays are fundamental data types in MATLAB and can be vectors, matrices, or multidimensional. Variables are used to store information in the workspace and can represent different data types. Common operations include arithmetic, functions, and following the
1. A giant python swallowed an alligator in Everglades National Park, Florida, according to an article in yesterday's New York Times.
2. The article was titled "Invasion of the Giant Pythons" from PBS Nature.
3. The document provided a brief news item about an incident of a giant python eating an alligator in Florida's Everglades National Park.
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports operations on matrices and vectors. Basic math, logical, and relational operators are covered.
- The document discusses plotting, flow control using if/else, switch/case and loops, writing M-files including functions, and saving and loading workspace and data files.
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports vectors, scalars, and relational, logical, and math operators on matrices. Functions include trigonometric, exponential, logical, and matrix functions.
- Plots can be generated by passing vectors to plot, and annotated using commands like title, xlabel, ylabel, and legend. Flow control includes if/
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports operations on matrices and vectors. Basic math, logical, and relational operators are supported.
- Functions include trigonometric, exponential, logical, matrix creation and manipulation, and plotting functions. Flow control includes if/else statements and for/while loops.
- M-files can contain scripts of
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports operations on matrices and vectors. Basic math, logical, and relational operators are covered.
- The document discusses plotting, flow control using if/else, switch/case and loops, writing M-files including functions, and saving and loading workspace and data files.
This document provides an overview of MATLAB, including:
- MATLAB is a program for numerical computation originally designed for linear algebra problems using matrices. It has since expanded to other types of scientific computations and graphics.
- The main components of the MATLAB interface are the command window, workspace, history, and editor. Help is accessed using commands like help, doc, and demo.
- MATLAB treats all variables as matrices and supports vectors, scalars, and relational, logical, and math operators on matrices. Functions include trigonometric, exponential, logical, and matrix functions.
- Plots can be generated by passing vectors to plot, and annotated using commands like title, xlabel, ylabel, and legend. Flow control includes if/
MATLAB is an integrated technical computing environment used for numeric computation, visualization, and programming. It contains mathematical and graphical functions as well as tools for algorithm development, data analysis, visualization, and numeric computation. MATLAB can be used for a wide range of applications including signal and image processing, communications, control design, test and measurement. It also contains toolboxes for tasks in various domains like signal processing, control systems, computational finance, computer vision etc.
Python 3.0 introduces many backwards incompatible changes to the Python syntax and features to remove previous design mistakes and improve the language. Some key changes include print becoming a function, the introduction of bytes as a separate type from str, and the addition of the nonlocal keyword to allow modifying variables in nested functions. The document provides examples of how to port Python 2 code to Python 3 using the 2to3 refactoring tool.
MATLAB is an integrated technical computing environment for numeric computation, advanced graphics and visualization, and programming. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation and execution of scripts and functions. The MATLAB desktop provides the command window, editor, workspace and other tools. Key features include support for multidimensional arrays, mathematical functions, plotting, scripting and conditional/loop control statements.
Matlab is an interactive computing environment for numerical computation, visualization, and programming. The document provides an introduction and overview of Matlab, including what Matlab is, the Matlab screen interface, variables and arrays, basic math operations, plotting functions, control structures like if/else and for loops, using m-files, and writing user-defined functions. Key features of Matlab covered are the command window, workspace, command history, generating matrices and vectors, element-wise operations, relational and logical operators, and file input/output statements.
i. The linear convolution of two sequences was calculated using the conv command in MATLAB. The input sequences, individual sequences, and convolved output were plotted.
ii. Linear convolution was also calculated using the DFT and IDFT. The sequences were padded with zeros and transformed to the frequency domain using FFT. The transformed sequences were multiplied and inverse transformed using IFFT to obtain the circular convolution result.
iii. The circular convolution result using DFT/IDFT was the same as the linear convolution using the conv command, demonstrating the equivalence between linear and circular convolution in the frequency domain.
This lab manual covers MATLAB and digital signal processing concepts. It includes:
1) An introduction to MATLAB including basic commands, functions, vectors, matrices and operations.
2) Digital signal processing concepts like sampling, discrete time signals, linear convolution using the conv command are explained.
3) Experiments are included to verify the sampling theorem and study linear convolution of sequences.
Conference Paper:IMAGE PROCESSING AND OBJECT DETECTION APPLICATION: INSURANCE...Dr. Volkan OBAN
1) The document discusses using image processing and object detection techniques for insurance claims processing and underwriting. It aims to allow insurers to realistically assess images of damaged objects and claims.
2) Artificial intelligence, including computer vision, has been widely adopted in the insurance industry to analyze data like images, extract relevant information, detect fraud, and predict costs. Computer vision can recognize objects in images and help route insurance inquiries.
3) The document examines several computer vision applications for insurance - image similarity, facial recognition, object detection, and damage detection from images. It asserts that computer vision can expedite claims processing and improve key performance metrics for insurers.
Covid19py by Konstantinos Kamaropoulos
A tiny Python package for easy access to up-to-date Coronavirus (COVID-19, SARS-CoV-2) cases data.
ref:https://github.com/Kamaropoulos/COVID19Py
https://pypi.org/project/COVID19Py/?fbclid=IwAR0zFKe_1Y6Nm0ak1n0W1ucFZcVT4VBWEP4LOFHJP-DgoL32kx3JCCxkGLQ
This document provides examples of object detection output from a deep learning model. The examples detect objects like cars, trucks, people, and horses along with confidence scores. The document also mentions using Python and TensorFlow for object detection with deep learning. It is authored by Volkan Oban, a senior data scientist.
The document discusses using the lpSolveAPI package in R to solve linear programming problems. It provides three examples:
1) A farmer's profit maximization problem is modeled and solved using functions from lpSolveAPI like make.lp(), add.constraint(), and solve().
2) A simple minimization problem is created and solved to illustrate setting up the objective function and constraints.
3) A more complex problem is modeled to demonstrate setting sparse matrices, integer/binary variables, and customizing variable and constraint names.
"optrees" package in R and examples.(optrees:finds optimal trees in weighted ...Dr. Volkan OBAN
Finds optimal trees in weighted graphs. In
particular, this package provides solving tools for minimum cost spanning
tree problems, minimum cost arborescence problems, shortest path tree
problems and minimum cut tree problem.
by Volkan OBAN
k-means Clustering in Python
scikit-learn--Machine Learning in Python
from sklearn.cluster import KMeans
k-means clustering is a method of vector quantization, originally from signal processing, that is popular for cluster analysis in data mining. k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells.
The problem is computationally difficult (NP-hard); however, there are efficient heuristic algorithms that are commonly employed and converge quickly to a local optimum. These are usually similar to the expectation-maximization algorithm for mixtures of Gaussian distributions via an iterative refinement approach employed by both algorithms. Additionally, they both use cluster centers to model the data; however, k-means clustering tends to find clusters of comparable spatial extent, while the expectation-maximization mechanism allows clusters to have different shapes.[wikipedia]
ref: http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_iris.html
This document describes using time series analysis in R to model and forecast tractor sales data. The sales data is transformed using logarithms and differencing to make it stationary. An ARIMA(0,1,1)(0,1,1)[12] model is fitted to the data and produces forecasts for 36 months ahead. The forecasts are plotted along with the original sales data and 95% prediction intervals.
k-means Clustering and Custergram with R.
K Means Clustering is an unsupervised learning algorithm that tries to cluster data based on their similarity. Unsupervised learning means that there is no outcome to be predicted, and the algorithm just tries to find patterns in the data. In k means clustering, we have the specify the number of clusters we want the data to be grouped into. The algorithm randomly assigns each observation to a cluster, and finds the centroid of each cluster.
ref:https://www.r-bloggers.com/k-means-clustering-in-r/
ref:https://rpubs.com/FelipeRego/K-Means-Clustering
ref:https://www.r-bloggers.com/clustergram-visualization-and-diagnostics-for-cluster-analysis-r-code/
Data Science and its Relationship to Big Data and Data-Driven Decision MakingDr. Volkan OBAN
Data Science and its Relationship to Big Data and Data-Driven Decision Making
To cite this article:
Foster Provost and Tom Fawcett. Big Data. February 2013, 1(1): 51-59. doi:10.1089/big.2013.1508.
Foster Provost and Tom Fawcett
Published in Volume: 1 Issue 1: February 13, 2013
ref:http://online.liebertpub.com/doi/full/10.1089/big.2013.1508
https://www.researchgate.net/publication/256439081_Data_Science_and_Its_Relationship_to_Big_Data_and_Data-Driven_Decision_Making
The Pandas library provides easy-to-use data structures and analysis tools for Python. It uses NumPy and allows import of data into Series (one-dimensional arrays) and DataFrames (two-dimensional labeled data structures). Data can be accessed, filtered, and manipulated using indexing, booleans, and arithmetic operations. Pandas supports reading and writing data to common formats like CSV, Excel, SQL, and can help with data cleaning, manipulation, and analysis tasks.
ReporteRs package in R. forming powerpoint documents-an exampleDr. Volkan OBAN
This document contains examples of plots, FlexTables, and text generated with the ReporteRs package in R to create a PowerPoint presentation. A line plot is generated showing ozone levels over time. A FlexTable is created from the iris dataset with styled cells and borders. Sections of formatted text are added describing topics in data science, analytics, and machine learning.
ReporteRs package in R. forming powerpoint documents-an exampleDr. Volkan OBAN
This document contains examples of plots, FlexTables, and text generated with the ReporteRs package in R to create a PowerPoint presentation. A line plot is generated showing ozone levels over time. A FlexTable is created from the iris dataset with styled cells and borders. Sections of formatted text are added describing topics in data science, analytics, and machine learning.
R Machine Learning packages( generally used)
prepared by Volkan OBAN
reference:
https://github.com/josephmisiti/awesome-machine-learning#r-general-purpose
Unblocking The Main Thread - Solving ANRs and Frozen FramesSinan KOZAK
In the realm of Android development, the main thread is our stage, but too often, it becomes a battleground where performance issues arise, leading to ANRS, frozen frames, and sluggish Uls. As we strive for excellence in user experience, understanding and optimizing the main thread becomes essential to prevent these common perforrmance bottlenecks. We have strategies and best practices for keeping the main thread uncluttered. We'll examine the root causes of performance issues and techniques for monitoring and improving main thread health as wel as app performance. In this talk, participants will walk away with practical knowledge on enhancing app performance by mastering the main thread. We'll share proven approaches to eliminate real-life ANRS and frozen frames to build apps that deliver butter smooth experience.
In May 2024, globally renowned natural diamond crafting company Shree Ramkrishna Exports Pvt. Ltd. (SRK) became the first company in the world to achieve GNFZ’s final net zero certification for existing buildings, for its two two flagship crafting facilities SRK House and SRK Empire. Initially targeting 2030 to reach net zero, SRK joined forces with the Global Network for Zero (GNFZ) to accelerate its target to 2024 — a trailblazing achievement toward emissions elimination.
Response & Safe AI at Summer School of AI at IIITHIIIT Hyderabad
Talk covering Guardrails , Jailbreak, What is an alignment problem? RLHF, EU AI Act, Machine & Graph unlearning, Bias, Inconsistency, Probing, Interpretability, Bias
Social media management system project report.pdfKamal Acharya
The project "Social Media Platform in Object-Oriented Modeling" aims to design
and model a robust and scalable social media platform using object-oriented
modeling principles. In the age of digital communication, social media platforms
have become indispensable for connecting people, sharing content, and fostering
online communities. However, their complex nature requires meticulous planning
and organization.This project addresses the challenge of creating a feature-rich and
user-friendly social media platform by applying key object-oriented modeling
concepts. It entails the identification and definition of essential objects such as
"User," "Post," "Comment," and "Notification," each encapsulating specific
attributes and behaviors. Relationships between these objects, such as friendships,
content interactions, and notifications, are meticulously established.The project
emphasizes encapsulation to maintain data integrity, inheritance for shared behaviors
among objects, and polymorphism for flexible content handling. Use case diagrams
depict user interactions, while sequence diagrams showcase the flow of interactions
during critical scenarios. Class diagrams provide an overarching view of the system's
architecture, including classes, attributes, and methods .By undertaking this project,
we aim to create a modular, maintainable, and user-centric social media platform that
adheres to best practices in object-oriented modeling. Such a platform will offer users
a seamless and secure online social experience while facilitating future enhancements
and adaptability to changing user needs.
An Internet Protocol address (IP address) is a logical numeric address that is assigned to every single computer, printer, switch, router, tablets, smartphones or any other device that is part of a TCP/IP-based network.
Types of IP address-
Dynamic means "constantly changing “ .dynamic IP addresses aren't more powerful, but they can change.
Static means staying the same. Static. Stand. Stable. Yes, static IP addresses don't change.
Most IP addresses assigned today by Internet Service Providers are dynamic IP addresses. It's more cost effective for the ISP and you.
A brief introduction to quadcopter (drone) working. It provides an overview of flight stability, dynamics, general control system block diagram, and the electronic hardware.
A brand new catalog for the 2024 edition of IWISS. We have enriched our product range and have more innovations in electrician tools, plumbing tools, wire rope tools and banding tools. Let's explore together!
20CDE09- INFORMATION DESIGN
UNIT I INCEPTION OF INFORMATION DESIGN
Introduction and Definition
History of Information Design
Need of Information Design
Types of Information Design
Identifying audience
Defining the audience and their needs
Inclusivity and Visual impairment
Case study.
1. MATLAB commands in numerical Python (NumPy) 1
Vidar Bronken Gundersen /mathesaurus.sf.net
MATLAB commands in numerical Python (NumPy)
Copyright c Vidar Bronken Gundersen
Permission is granted to copy, distribute and/or modify this document as long as the above attribution is kept and the resulting work is distributed under a license identical to this one.
The idea of this document (and the corresponding xml instance) is to provide a quick reference
for switching from matlab
to an open-source environment, such as Python, Scilab, Octave and Gnuplot, or R for numeric processing and data visualisation.
Where Octave and Scilab commands are omitted, expect Matlab compatibility, and similarly where non given use the generic command.
Time-stamp: --T:: vidar
1 Help
Desc. matlab/Octave Python R
Browse help interactively doc
Octave: help -i % browse with Info
help() help.start()
Help on using help help help or doc doc help help()
Help for a function help plot help(plot) or ?plot help(plot) or ?plot
Help for a toolbox/library package help splines or doc splines help(pylab) help(package=’splines’)
Demonstration examples demo demo()
Example using a function example(plot)
1.1 Searching available documentation
Desc. matlab/Octave Python R
Search help files lookfor plot help.search(’plot’)
Find objects by partial name apropos(’plot’)
List available packages help help(); modules [Numeric] library()
Locate functions which plot help(plot) find(plot)
List available methods for a function methods(plot)
1.2 Using interactively
Desc. matlab/Octave Python R
Start session Octave: octave -q ipython -pylab Rgui
Auto completion Octave: TAB or M-? TAB
Run code from file foo(.m) execfile(’foo.py’) or run foo.py source(’foo.R’)
Command history Octave: history hist -n history()
Save command history diary on [..] diary off savehistory(file=".Rhistory")
End session exit or quit CTRL-D
CTRL-Z # windows
sys.exit()
q(save=’no’)
2 Operators
Desc. matlab/Octave Python R
Help on operator syntax help - help(Syntax)
References: Hankin, Robin. R for Octave users (), available from http://cran.r-project.org/doc/contrib/R-and-octave-.txt (accessed ..); Martelli, Alex. Python in a Nutshell (O’Reilly, );
Oliphant, Travis. Guide to NumPy (Trelgol, ); Hunter, John. The Matplotlib User’s Guide (), available from http://matplotlib.sf.net/ (accessed ..); Langtangen, Hans Petter. Python
Scripting for Computational Science (Springer, ); Ascher et al.: Numeric Python manual (), available from http://numeric.scipy.org/numpy.pdf (accessed ..); Moler, Cleve. Numerical
Computing with MATLAB (MathWorks, ), available from http://www.mathworks.com/moler/ (accessed ..); Eaton, John W. Octave Quick Reference (); Merrit, Ethan. Demo scripts for
gnuplot version 4.0 (), available from http://gnuplot.sourceforge.net/demo/ (accessed ..); Woo, Alex. Gnuplot Quick Reference (), available from http://www.gnuplot.info/docs/gpcard.pdf
(accessed ..); Venables & Smith: An Introduction to R (), available from http://cran.r-project.org/doc/manuals/R-intro.pdf (accessed ..); Short, Tom. R reference card (), available
from http://www.rpad.org/Rpad/R-refcard.pdf (accessed ..).
2. MATLAB commands in numerical Python (NumPy) 2
Vidar Bronken Gundersen /mathesaurus.sf.net
2.1 Arithmetic operators
Desc. matlab/Octave Python R
Assignment; defining a number a=1; b=2; a=1; b=1 a<-1; b<-2
Addition a + b a + b or add(a,b) a + b
Subtraction a - b a - b or subtract(a,b) a - b
Multiplication a * b a * b or multiply(a,b) a * b
Division a / b a / b or divide(a,b) a / b
Power, ab
a .^ b a ** b
power(a,b)
pow(a,b)
a ^ b
Remainder rem(a,b) a % b
remainder(a,b)
fmod(a,b)
a %% b
Integer division a %/% b
In place operation to save array creation
overhead
Octave: a+=1 a+=b or add(a,b,a)
Factorial, n! factorial(a) factorial(a)
2.2 Relational operators
Desc. matlab/Octave Python R
Equal a == b a == b or equal(a,b) a == b
Less than a < b a < b or less(a,b) a < b
Greater than a > b a > b or greater(a,b) a > b
Less than or equal a <= b a <= b or less_equal(a,b) a <= b
Greater than or equal a >= b a >= b or greater_equal(a,b) a >= b
Not Equal a ~= b a != b or not_equal(a,b) a != b
2.3 Logical operators
Desc. matlab/Octave Python R
Short-circuit logical AND a && b a and b a && b
Short-circuit logical OR a || b a or b a || b
Element-wise logical AND a & b or and(a,b) logical_and(a,b) or a and b a & b
Element-wise logical OR a | b or or(a,b) logical_or(a,b) or a or b a | b
Logical EXCLUSIVE OR xor(a, b) logical_xor(a,b) xor(a, b)
Logical NOT ~a or not(a)
Octave: ~a or !a
logical_not(a) or not a !a
True if any element is nonzero any(a)
True if all elements are nonzero all(a)
2.4 root and logarithm
Desc. matlab/Octave Python R
Square root sqrt(a) math.sqrt(a) sqrt(a)
√
a
Logarithm, base e (natural) log(a) math.log(a) log(a) ln a = loge a
Logarithm, base log10(a) math.log10(a) log10(a) log10 a
Logarithm, base (binary) log2(a) math.log(a, 2) log2(a) log2 a
Exponential function exp(a) math.exp(a) exp(a) ea
3. MATLAB commands in numerical Python (NumPy) 3
Vidar Bronken Gundersen /mathesaurus.sf.net
2.5 Round off
Desc. matlab/Octave Python R
Round round(a) around(a) or math.round(a) round(a)
Round up ceil(a) ceil(a) ceil(a)
Round down floor(a) floor(a) floor(a)
Round towards zero fix(a) fix(a)
2.6 Mathematical constants
Desc. matlab/Octave Python R
π = 3.141592 pi math.pi pi
e = 2.718281 exp(1) math.e or math.exp(1) exp(1)
2.6.1 Missing values; IEEE-754 floating point status flags
Desc. matlab/Octave Python R
Not a Number NaN nan
Infinity, ∞ Inf inf
Infinity, +∞ plus_inf
Infinity, −∞ minus_inf
Plus zero, +0 plus_zero
Minus zero, −0 minus_zero
2.7 Complex numbers
Desc. matlab/Octave Python R
Imaginary unit i z = 1j 1i i =
√
−1
A complex number, 3 + 4i z = 3+4i z = 3+4j or z = complex(3,4) z <- 3+4i
Absolute value (modulus) abs(z) abs(3+4j) abs(3+4i) or Mod(3+4i)
Real part real(z) z.real Re(3+4i)
Imaginary part imag(z) z.imag Im(3+4i)
Argument arg(z) Arg(3+4i)
Complex conjugate conj(z) z.conj(); z.conjugate() Conj(3+4i)
2.8 Trigonometry
Desc. matlab/Octave Python R
Arctangent, arctan(b/a) atan(a,b) atan2(b,a) atan2(b,a)
Hypotenus; Euclidean distance hypot(x,y) x2 + y2
2.9 Generate random numbers
Desc. matlab/Octave Python R
Uniform distribution rand(1,10) random.random((10,))
random.uniform((10,))
runif(10)
Uniform: Numbers between and 2+5*rand(1,10) random.uniform(2,7,(10,)) runif(10, min=2, max=7)
Uniform: , array rand(6) random.uniform(0,1,(6,6)) matrix(runif(36),6)
Normal distribution randn(1,10) random.standard_normal((10,)) rnorm(10)
4. MATLAB commands in numerical Python (NumPy) 4
Vidar Bronken Gundersen /mathesaurus.sf.net
3 Vectors
Desc. matlab/Octave Python R
Row vector, 1 × n-matrix a=[2 3 4 5]; a=array([2,3,4,5]) a <- c(2,3,4,5)
Column vector, m × 1-matrix adash=[2 3 4 5]’; array([2,3,4,5])[:,NewAxis]
array([2,3,4,5]).reshape(-1,1)
r_[1:10,’c’]
adash <- t(c(2,3,4,5))
3.1 Sequences
Desc. matlab/Octave Python R
,,, ... , 1:10 arange(1,11, dtype=Float)
range(1,11)
seq(10) or 1:10
.,.,., ... ,. 0:9 arange(10.) seq(0,length=10)
,,, 1:3:10 arange(1,11,3) seq(1,10,by=3)
,,, ... , 10:-1:1 arange(10,0,-1) seq(10,1) or 10:1
,,, 10:-3:1 arange(10,0,-3) seq(from=10,to=1,by=-3)
Linearly spaced vector of n= points linspace(1,10,7) linspace(1,10,7) seq(1,10,length=7)
Reverse reverse(a) a[::-1] or rev(a)
Set all values to same scalar value a(:) = 3 a.fill(3), a[:] = 3
3.2 Concatenation (vectors)
Desc. matlab/Octave Python R
Concatenate two vectors [a a] concatenate((a,a)) c(a,a)
[1:4 a] concatenate((range(1,5),a), axis=1) c(1:4,a)
3.3 Repeating
Desc. matlab/Octave Python R
, [a a] concatenate((a,a)) rep(a,times=2)
, , a.repeat(3) or rep(a,each=3)
, , a.repeat(a) or rep(a,a)
3.4 Miss those elements out
Desc. matlab/Octave Python R
miss the first element a(2:end) a[1:] a[-1]
miss the tenth element a([1:9]) a[-10]
miss ,,, ... a[-seq(1,50,3)]
last element a(end) a[-1]
last two elements a(end-1:end) a[-2:]
3.5 Maximum and minimum
Desc. matlab/Octave Python R
pairwise max max(a,b) maximum(a,b) pmax(a,b)
max of all values in two vectors max([a b]) concatenate((a,b)).max() max(a,b)
[v,i] = max(a) v,i = a.max(0),a.argmax(0) v <- max(a) ; i <- which.max(a)
6. MATLAB commands in numerical Python (NumPy) 6
Vidar Bronken Gundersen /mathesaurus.sf.net
4.3 Reshape and flatten matrices
Desc. matlab/Octave Python R
Reshaping (rows first) reshape(1:6,3,2)’; arange(1,7).reshape(2,-1)
a.setshape(2,3)
matrix(1:6,nrow=3,byrow=T)
1 2 3
4 5 6
Reshaping (columns first) reshape(1:6,2,3); arange(1,7).reshape(-1,2).transpose() matrix(1:6,nrow=2)
array(1:6,c(2,3))
1 3 5
2 4 6
Flatten to vector (by rows, like comics) a’(:) a.flatten() or as.vector(t(a)) 1 2 3 4 5 6
Flatten to vector (by columns) a(:) a.flatten(1) as.vector(a) 1 4 2 5 3 6
Flatten upper triangle (by columns) vech(a) a[row(a) <= col(a)]
4.4 Shared data (slicing)
Desc. matlab/Octave Python R
Copy of a b = a b = a.copy() b = a
4.5 Indexing and accessing elements (Python: slicing)
Desc. matlab/Octave Python R
Input is a , array a = [ 11 12 13 14 ...
21 22 23 24 ...
31 32 33 34 ]
a = array([[ 11, 12, 13, 14 ],
[ 21, 22, 23, 24 ],
[ 31, 32, 33, 34 ]])
a <- rbind(c(11, 12, 13, 14),
c(21, 22, 23, 24),
c(31, 32, 33, 34))
a11 a12 a13 a14
a21 a22 a23 a24
a31 a32 a33 a34
Element , (row,col) a(2,3) a[1,2] a[2,3] a23
First row a(1,:) a[0,] a[1,] a11 a12 a13 a14
First column a(:,1) a[:,0] a[,1]
a11
a21
a31
Array as indices a([1 3],[1 4]); a.take([0,2]).take([0,3], axis=1)
a11 a14
a31 a34
All, except first row a(2:end,:) a[1:,] a[-1,]
a21 a22 a23 a24
a31 a32 a33 a34
Last two rows a(end-1:end,:) a[-2:,]
a21 a22 a23 a24
a31 a32 a33 a34
Strides: Every other row a(1:2:end,:) a[::2,:]
a11 a12 a13 a14
a31 a32 a33 a34
Third in last dimension (axis) a[...,2]
All, except row,column (,) a[-2,-3]
a11 a13 a14
a31 a33 a34
Remove one column a(:,[1 3 4]) a.take([0,2,3],axis=1) a[,-2]
a11 a13 a14
a21 a23 a24
a31 a33 a34
Diagonal a.diagonal(offset=0) a11 a22 a33 a44
7. MATLAB commands in numerical Python (NumPy) 7
Vidar Bronken Gundersen /mathesaurus.sf.net
4.6 Assignment
Desc. matlab/Octave Python R
a(:,1) = 99 a[:,0] = 99 a[,1] <- 99
a(:,1) = [99 98 97]’ a[:,0] = array([99,98,97]) a[,1] <- c(99,98,97)
Clipping: Replace all elements over a(a>90) = 90; (a>90).choose(a,90)
a.clip(min=None, max=90)
a[a>90] <- 90
Clip upper and lower values a.clip(min=2, max=5)
4.7 Transpose and inverse
Desc. matlab/Octave Python R
Transpose a’ a.conj().transpose() t(a)
Non-conjugate transpose a.’ or transpose(a) a.transpose()
Determinant det(a) linalg.det(a) or det(a)
Inverse inv(a) linalg.inv(a) or solve(a)
Pseudo-inverse pinv(a) linalg.pinv(a) ginv(a)
Norms norm(a) norm(a)
Eigenvalues eig(a) linalg.eig(a)[0] eigen(a)$values
Singular values svd(a) linalg.svd(a) svd(a)$d
Cholesky factorization chol(a) linalg.cholesky(a)
Eigenvectors [v,l] = eig(a) linalg.eig(a)[1] eigen(a)$vectors
Rank rank(a) rank(a) rank(a)
4.8 Sum
Desc. matlab/Octave Python R
Sum of each column sum(a) a.sum(axis=0) apply(a,2,sum)
Sum of each row sum(a’) a.sum(axis=1) apply(a,1,sum)
Sum of all elements sum(sum(a)) a.sum() sum(a)
Sum along diagonal a.trace(offset=0)
Cumulative sum (columns) cumsum(a) a.cumsum(axis=0) apply(a,2,cumsum)
8. MATLAB commands in numerical Python (NumPy) 8
Vidar Bronken Gundersen /mathesaurus.sf.net
4.9 Sorting
Desc. matlab/Octave Python R
Example data a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ] a = array([[4,3,2],[2,8,6],[1,4,7]])
4 3 2
2 8 6
1 4 7
Flat and sorted sort(a(:)) a.ravel().sort() or t(sort(a))
1 2 2
3 4 4
6 7 8
Sort each column sort(a) a.sort(axis=0) or msort(a) apply(a,2,sort)
1 3 2
2 4 6
4 8 7
Sort each row sort(a’)’ a.sort(axis=1) t(apply(a,1,sort))
2 3 4
2 6 8
1 4 7
Sort rows (by first row) sortrows(a,1) a[a[:,0].argsort(),]
1 4 7
2 8 6
4 3 2
Sort, return indices a.ravel().argsort() order(a)
Sort each column, return indices a.argsort(axis=0)
Sort each row, return indices a.argsort(axis=1)
4.10 Maximum and minimum
Desc. matlab/Octave Python R
max in each column max(a) a.max(0) or amax(a [,axis=0]) apply(a,2,max)
max in each row max(a’) a.max(1) or amax(a, axis=1) apply(a,1,max)
max in array max(max(a)) a.max() or max(a)
return indices, i [v i] = max(a) i <- apply(a,1,which.max)
pairwise max max(b,c) maximum(b,c) pmax(b,c)
cummax(a) apply(a,2,cummax)
max-to-min range a.ptp(); a.ptp(0)
4.11 Matrix manipulation
Desc. matlab/Octave Python R
Flip left-right fliplr(a) fliplr(a) or a[:,::-1] a[,4:1]
Flip up-down flipud(a) flipud(a) or a[::-1,] a[3:1,]
Rotate degrees rot90(a) rot90(a)
Repeat matrix: [ a a a ; a a a ] repmat(a,2,3)
Octave: kron(ones(2,3),a)
kron(ones((2,3)),a) kronecker(matrix(1,2,3),a)
Triangular, upper triu(a) triu(a) a[lower.tri(a)] <- 0
Triangular, lower tril(a) tril(a) a[upper.tri(a)] <- 0
4.12 Equivalents to ”size”
Desc. matlab/Octave Python R
Matrix dimensions size(a) a.shape or a.getshape() dim(a)
Number of columns size(a,2) or length(a) a.shape[1] or size(a, axis=1) ncol(a)
Number of elements length(a(:)) a.size or size(a[, axis=None]) prod(dim(a))
Number of dimensions ndims(a) a.ndim
Number of bytes used in memory a.nbytes object.size(a)
9. MATLAB commands in numerical Python (NumPy) 9
Vidar Bronken Gundersen /mathesaurus.sf.net
4.13 Matrix- and elementwise- multiplication
Desc. matlab/Octave Python R
Elementwise operations a .* b a * b or multiply(a,b) a * b
1 5
9 16
Matrix product (dot product) a * b matrixmultiply(a,b) a %*% b
7 10
15 22
Inner matrix vector multiplication a · b inner(a,b) or
5 11
11 25
Outer product outer(a,b) or outer(a,b) or a %o% b
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
Cross product crossprod(a,b) or t(a) %*% b
10 14
14 20
Kronecker product kron(a,b) kron(a,b) kronecker(a,b)
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
Matrix division, b·a−1
a / b
Left matrix division, b−1
·a
(solve linear equations)
a b linalg.solve(a,b) solve(a,b) Ax = b
Vector dot product vdot(a,b)
Cross product cross(a,b)
4.14 Find; conditional indexing
Desc. matlab/Octave Python R
Non-zero elements, indices find(a) a.ravel().nonzero() which(a != 0)
Non-zero elements, array indices [i j] = find(a) (i,j) = a.nonzero()
(i,j) = where(a!=0)
which(a != 0, arr.ind=T)
Vector of non-zero values [i j v] = find(a) v = a.compress((a!=0).flat)
v = extract(a!=0,a)
ij <- which(a != 0, arr.ind=T); v <- a[ij]
Condition, indices find(a>5.5) (a>5.5).nonzero() which(a>5.5)
Return values a.compress((a>5.5).flat) ij <- which(a>5.5, arr.ind=T); v <- a[ij]
Zero out elements above . a .* (a>5.5) where(a>5.5,0,a) or a * (a>5.5)
Replace values a.put(2,indices)
5 Multi-way arrays
Desc. matlab/Octave Python R
Define a -way array a = cat(3, [1 2; 1 2],[3 4; 3 4]); a = array([[[1,2],[1,2]], [[3,4],[3,4]]])
a(1,:,:) a[0,...]
10. MATLAB commands in numerical Python (NumPy) 10
Vidar Bronken Gundersen /mathesaurus.sf.net
6 File input and output
Desc. matlab/Octave Python R
Reading from a file (d) f = load(’data.txt’) f = fromfile("data.txt")
f = load("data.txt")
f <- read.table("data.txt")
Reading from a file (d) f = load(’data.txt’) f = load("data.txt") f <- read.table("data.txt")
Reading fram a CSV file (d) x = dlmread(’data.csv’, ’;’) f = load(’data.csv’, delimiter=’;’) f <- read.table(file="data.csv", sep=";")
Writing to a file (d) save -ascii data.txt f save(’data.csv’, f, fmt=’%.6f’, delimiter=’;’)write(f,file="data.txt")
Writing to a file (d) f.tofile(file=’data.csv’, format=’%.6f’, sep=’;’)
Reading from a file (d) f = fromfile(file=’data.csv’, sep=’;’)
7 Plotting
7.1 Basic x-y plots
Desc. matlab/Octave Python R
d line plot plot(a) plot(a) plot(a, type="l")
0 20 40 60 80 100
-4
-3
-2
-1
0
1
2
3
4
d scatter plot plot(x(:,1),x(:,2),’o’) plot(x[:,0],x[:,1],’o’) plot(x[,1],x[,2])
4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0
2.0
2.5
3.0
3.5
4.0
4.5
Two graphs in one plot plot(x1,y1, x2,y2) plot(x1,y1,’bo’, x2,y2,’go’)
4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0
1
2
3
4
5
6
7
Overplotting: Add new plots to current plot(x1,y1)
hold on
plot(x2,y2)
plot(x1,y1,’o’)
plot(x2,y2,’o’)
show() # as normal
plot(x1,y1)
matplot(x2,y2,add=T)
subplots subplot(211) subplot(211)
Plotting symbols and color plot(x,y,’ro-’) plot(x,y,’ro-’) plot(x,y,type="b",col="red")
11. MATLAB commands in numerical Python (NumPy) 11
Vidar Bronken Gundersen /mathesaurus.sf.net
7.1.1 Axes and titles
Desc. matlab/Octave Python R
Turn on grid lines grid on grid() grid()
: aspect ratio axis equal
Octave:
axis(’equal’)
replot
figure(figsize=(6,6)) plot(c(1:10,10:1), asp=1)
Set axes manually axis([ 0 10 0 5 ]) axis([ 0, 10, 0, 5 ]) plot(x,y, xlim=c(0,10), ylim=c(0,5))
Axis labels and titles title(’title’)
xlabel(’x-axis’)
ylabel(’y-axis’)
plot(1:10, main="title",
xlab="x-axis", ylab="y-axis")
Insert text text(2,25,’hello’)
7.1.2 Log plots
Desc. matlab/Octave Python R
logarithmic y-axis semilogy(a) semilogy(a) plot(x,y, log="y")
logarithmic x-axis semilogx(a) semilogx(a) plot(x,y, log="x")
logarithmic x and y axes loglog(a) loglog(a) plot(x,y, log="xy")
7.1.3 Filled plots and bar plots
Desc. matlab/Octave Python R
Filled plot fill(t,s,’b’, t,c,’g’)
Octave: % fill has a bug?
fill(t,s,’b’, t,c,’g’, alpha=0.2) plot(t,s, type="n", xlab="", ylab="")
polygon(t,s, col="lightblue")
polygon(t,c, col="lightgreen")
Stem-and-Leaf plot stem(x[,3])
5 5
6 71
7 033
8 00113345567889
9 0133566677788
10 32674
7.1.4 Functions
Desc. matlab/Octave Python R
Defining functions f = inline(’sin(x/3) - cos(x/5)’) f <- function(x) sin(x/3) - cos(x/5) f(x) = sin x
3 − cos x
5
Plot a function for given range ezplot(f,[0,40])
fplot(’sin(x/3) - cos(x/5)’,[0,40])
Octave: % no ezplot
x = arrayrange(0,40,.5)
y = sin(x/3) - cos(x/5)
plot(x,y, ’o’)
plot(f, xlim=c(0,40), type=’p’)
q
q
q
q
q
q
q
q
q
q
q
q
q
q
qq
qqq
q
q
q
q
q
q
q
q
q
q
q
qq
qqqq
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
qq
qqq
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
qqqq
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
q
0 10 20 30 40
−2.0−1.5−1.0−0.50.00.51.0
x
f(x)
14. MATLAB commands in numerical Python (NumPy) 14
Vidar Bronken Gundersen /mathesaurus.sf.net
7.4.2 Perspective plots of surfaces over the x-y plane
Desc. matlab/Octave Python R
n=-2:.1:2;
[x,y] = meshgrid(n,n);
z=x.*exp(-x.^2-y.^2);
n=arrayrange(-2,2,.1)
[x,y] = meshgrid(n,n)
z = x*power(math.e,-x**2-y**2)
f <- function(x,y) x*exp(-x^2-y^2)
n <- seq(-2,2, length=40)
z <- outer(n,n,f)
f(x, y) = xe−x2−y2
Mesh plot mesh(z) persp(x,y,z,
theta=30, phi=30, expand=0.6,
ticktype=’detailed’)
x
−2
−1
0
1
2
y
−2
−1
0
1
2
z
−0.4
−0.2
0.0
0.2
0.4
Surface plot surf(x,y,z) or surfl(x,y,z)
Octave: % no surfl()
persp(x,y,z,
theta=30, phi=30, expand=0.6,
col=’lightblue’, shade=0.75, ltheta=120,
ticktype=’detailed’)
x
−2
−1
0
1
2
y
−2
−1
0
1
2
z
−0.4
−0.2
0.0
0.2
0.4
7.4.3 Scatter (cloud) plots
Desc. matlab/Octave Python R
d scatter plot plot3(x,y,z,’k+’) cloud(z~x*y)
0
10
20
30
40
50
60
70
80
90
100
-60
-40
-20
0
20
40
60
80
-80
-60
-40
-20
0
20
40
60
80
’icc-gamut.csv’
15. MATLAB commands in numerical Python (NumPy) 15
Vidar Bronken Gundersen /mathesaurus.sf.net
7.5 Save plot to a graphics file
Desc. matlab/Octave Python R
PostScript plot(1:10)
print -depsc2 foo.eps
Octave:
gset output "foo.eps"
gset terminal postscript eps
plot(1:10)
savefig(’foo.eps’) postscript(file="foo.eps")
plot(1:10)
dev.off()
PDF savefig(’foo.pdf’) pdf(file=’foo.pdf’)
SVG (vector graphics for www) savefig(’foo.svg’) devSVG(file=’foo.svg’)
PNG (raster graphics) print -dpng foo.png savefig(’foo.png’) png(filename = "Rplot%03d.png"
8 Data analysis
8.1 Set membership operators
Desc. matlab/Octave Python R
Create sets a = [ 1 2 2 5 2 ];
b = [ 2 3 4 ];
a = array([1,2,2,5,2])
b = array([2,3,4])
a = set([1,2,2,5,2])
b = set([2,3,4])
a <- c(1,2,2,5,2)
b <- c(2,3,4)
Set unique unique(a) unique1d(a)
unique(a)
set(a)
unique(a) 1 2 5
Set union union(a,b) union1d(a,b)
a.union(b)
union(a,b)
Set intersection intersect(a,b) intersect1d(a)
a.intersection(b)
intersect(a,b)
Set difference setdiff(a,b) setdiff1d(a,b)
a.difference(b)
setdiff(a,b)
Set exclusion setxor(a,b) setxor1d(a,b)
a.symmetric_difference(b)
setdiff(union(a,b),intersect(a,b))
True for set member ismember(2,a) 2 in a
setmember1d(2,a)
contains(a,2)
is.element(2,a) or 2 %in% a
16. MATLAB commands in numerical Python (NumPy) 16
Vidar Bronken Gundersen /mathesaurus.sf.net
8.2 Statistics
Desc. matlab/Octave Python R
Average mean(a) a.mean(axis=0)
mean(a [,axis=0])
apply(a,2,mean)
Median median(a) median(a) or median(a [,axis=0]) apply(a,2,median)
Standard deviation std(a) a.std(axis=0) or std(a [,axis=0]) apply(a,2,sd)
Variance var(a) a.var(axis=0) or var(a) apply(a,2,var)
Correlation coefficient corr(x,y) correlate(x,y) or corrcoef(x,y) cor(x,y)
Covariance cov(x,y) cov(x,y) cov(x,y)
8.3 Interpolation and regression
Desc. matlab/Octave Python R
Straight line fit z = polyval(polyfit(x,y,1),x)
plot(x,y,’o’, x,z ,’-’)
(a,b) = polyfit(x,y,1)
plot(x,y,’o’, x,a*x+b,’-’)
z <- lm(y~x)
plot(x,y)
abline(z)
Linear least squares y = ax + b a = xy linalg.lstsq(x,y) solve(a,b)
Polynomial fit polyfit(x,y,3) polyfit(x,y,3)
8.4 Non-linear methods
8.4.1 Polynomials, root finding
Desc. matlab/Octave Python R
Polynomial poly()
Find zeros of polynomial roots([1 -1 -1]) roots() polyroot(c(1,-1,-1)) x2
− x − 1 = 0
Find a zero near x = 1 f = inline(’1/x - (x-1)’)
fzero(f,1)
f(x) = 1
x − (x − 1)
Solve symbolic equations solve(’1/x = x-1’) 1
x = x − 1
Evaluate polynomial polyval([1 2 1 2],1:10) polyval(array([1,2,1,2]),arange(1,11))
8.4.2 Differential equations
Desc. matlab/Octave Python R
Discrete difference function and approxi-
mate derivative
diff(a) diff(x, n=1, axis=0)
Solve differential equations
8.5 Fourier analysis
Desc. matlab/Octave Python R
Fast fourier transform fft(a) fft(a) or fft(a)
Inverse fourier transform ifft(a) ifft(a) or fft(a, inverse=TRUE)
Linear convolution convolve(x,y)
9 Symbolic algebra; calculus
Desc. matlab/Octave Python R
Factorization factor()
17. MATLAB commands in numerical Python (NumPy) 17
Vidar Bronken Gundersen /mathesaurus.sf.net
10 Programming
Desc. matlab/Octave Python R
Script file extension .m .py .R
Comment symbol (rest of line) %
Octave: % or #
# #
Import library functions % must be in MATLABPATH
Octave: % must be in LOADPATH
from pylab import * library(RSvgDevice)
Eval string=’a=234’;
eval(string)
string="a=234"
eval(string)
string <- "a <- 234"
eval(parse(text=string))
10.1 Loops
Desc. matlab/Octave Python R
for-statement for i=1:5; disp(i); end for i in range(1,6): print(i) for(i in 1:5) print(i)
Multiline for statements for i=1:5
disp(i)
disp(i*2)
end
for i in range(1,6):
print(i)
print(i*2)
for(i in 1:5) {
print(i)
print(i*2)
}
10.2 Conditionals
Desc. matlab/Octave Python R
if-statement if 1>0 a=100; end if 1>0: a=100 if (1>0) a <- 100
if-else-statement if 1>0 a=100; else a=0; end
Ternary operator (if?true:false) ifelse(a>0,a,0) a > 0?a : 0
10.3 Debugging
Desc. matlab/Octave Python R
Most recent evaluated expression ans .Last.value
List variables loaded into memory whos or who objects()
Clear variable x from memory clear x or clear [all] rm(x)
Print disp(a) print a print(a)
10.4 Working directory and OS
Desc. matlab/Octave Python R
List files in directory dir or ls os.listdir(".") list.files() or dir()
List script files in directory what grep.grep("*.py") list.files(pattern=".r$")
Displays the current working directory pwd os.getcwd() getwd()
Change working directory cd foo os.chdir(’foo’) setwd(’foo’)
Invoke a System Command !notepad
Octave: system("notepad")
os.system(’notepad’)
os.popen(’notepad’)
system("notepad")
This document is still draft quality. Most shown d plots are made using Matplotlib, and d plots using R and Gnuplot, provided as examples only.
Version numbers and download url for software used: Python .., http://www.python.org/; NumPy .., http://numeric.scipy.org/; Matplotlib ., http://matplotlib.sf.net/; IPython ..,
http://ipython.scipy.org/; R .., http://www.r-project.org/; Octave .., http://www.octave.org/; Scilab ., http://www.scilab.org/; Gnuplot ., http://www.gnuplot.info/.
For referencing: Gundersen, Vidar Bronken. MATLAB commands in numerical Python (Oslo/Norway, ), available from: http://mathesaurus.sf.net/
Contributions are appreciated: The best way to do this is to edit the xml and submit patches to our tracker or forums.