Writing Your First Program ¶

In this section we will show you how to write a simple program in Matlab. To speed up understanding, we will write a program that replicates the plot generated in the “Visual Display” section.

  • If you didn’t complete the previous sections, you can download the data series HERE . Once you have downloaded the Matlab file, place it in your active Matlab “Current Folder”.
  • Writing a program for everything you do in Matlab is the most efficient way of operating within Matlab. A program allows you to replicate difficult processes quickly, save your work when it is not complete, fix mistakes before they become problems, help you remember how you solved a particular problem and much more.
  • Start writing a new program by clicking new script at the top left of the Matlab window

_images/newscript.png

  • It is always wise to place some notes at the top of your program describing the programs purpose. It is also a good idea to place comments around confusing parts of your code. There are often times when you will be working as a team and everyone writes code differently. Do yourself and your team members a favor and explain what you are doing.
  • “clear all” clears all variables from the Workspace
  • “close all” closes all open figures
  • “clc” clears the history of commands entered in the Command Window
  • Another important habit is to place a semi-colon ”;” at the end of every command in your program. This will surpress printing of the command in the Command Window. However, occationally it will be useful to allow the computer to print a particular command.
  • Type the commands in the script editor in the order that you would like Matlab to execute them:

_images/first1.png

  • It is important to notice that if your variables are not saved in a file like “data.mat”, they will be cleared by the first line of code
  • Once you have written your code you will need to save it. Click on “Save” near the upper left of your Matlab window. Let’s name the program “plotSP”
  • Once the file is saved you are free to run the program by clicking “Run” or by typing “plotSP” and enter in the command window

_images/run.png

  • You should get a figure that looks like:

_images/plot2.png

  • Suppose that after you look at the graph, you decide that the real interesting part of the series is the middle 2 quarters of the year. You can easily change your program to only print the middle two quarters of the year by changing the observation range to 64-189 (252/4=63).
  • To make this change in your program, change the range of dateNums and price as shown below:

_images/first2.png

  • Suppose further that you now love the data selection on the graph, but you don’t like the unused space. You can fix this by adding the command “axis tight”. For more information, see: Axis Scaling and Appearance

Saving Ouput ¶

  • You now love your data selection and your graph so much that you want to save it as a Portable Network Graphic file or ”.png”
  • First you need to save the figure as a variable. Place the command “fig1 = figure” before any plotting occurs (you could alternatively write fig1 = plot(x,y)). This action saves all the following figure commands to the variable fig1 .
  • To save the final figure, you will need to add the command “saveas(fig1,’plotSP.png’)” at the end of all the figure commands. This saves the variable fig1 as a file named “plotSP” of type ”.png”.
  • Once you have done all this, run the program again. You can view the .png file in your MATLAB folder, which is located in your “Documents” folder on Windows 7.
  • Don’t forget to update your description of the program as your program no longer plots the entire year; only the middle two quarters.
  • Your final program should look like this:

_images/first4.png

  • Your final output should look like this:

_images/plotSP.png

Table Of Contents

  • Patrick Herb
  • Introduction
  • Getting Started
  • Getting Help
  • Linear Algebra Review
  • Interacting & Saving Variables
  • Math with Matrices
  • Using Built-in Functions
  • Importing Data
  • Visual Display
  • Saving Ouput
  • Creating Functions
  • Simulating Data
  • Ordinary Least Squares
  • Monte Carlo
  • Matlab Functions Reference List

Enter search terms or a module, class or function name.

  • PRO Courses Guides New Tech Help Pro Expert Videos About wikiHow Pro Upgrade Sign In
  • EDIT Edit this Article
  • EXPLORE Tech Help Pro About Us Random Article Quizzes Request a New Article Community Dashboard This Or That Game Popular Categories Arts and Entertainment Artwork Books Movies Computers and Electronics Computers Phone Skills Technology Hacks Health Men's Health Mental Health Women's Health Relationships Dating Love Relationship Issues Hobbies and Crafts Crafts Drawing Games Education & Communication Communication Skills Personal Development Studying Personal Care and Style Fashion Hair Care Personal Hygiene Youth Personal Care School Stuff Dating All Categories Arts and Entertainment Finance and Business Home and Garden Relationship Quizzes Cars & Other Vehicles Food and Entertaining Personal Care and Style Sports and Fitness Computers and Electronics Health Pets and Animals Travel Education & Communication Hobbies and Crafts Philosophy and Religion Work World Family Life Holidays and Traditions Relationships Youth
  • Browse Articles
  • Learn Something New
  • Quizzes Hot
  • This Or That Game New
  • Train Your Brain
  • Explore More
  • Support wikiHow
  • About wikiHow
  • Log in / Sign up
  • Computers and Electronics
  • Programming

How to Write a Function and Call It in MATLAB

Last Updated: May 29, 2023

wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, volunteer authors worked to edit and improve it over time. This article has been viewed 79,592 times. Learn more...

Functions are the basis of all scripting and programming languages. With functions, you can make your applications do anything you want. Functions are very useful and necessary in all applications that are design in MATLAB. We will be designing the math function y = mx+ b which is known as the slope equation this equation if programmatically defined is helpful since we can just plug in the known inputs and the program will output the answer. This instruction set assumes you have basic knowledge of MATLAB, such as how to open a script file and how to perform simple data operations.

Things You Should Know

  • Start your script with function , followed by the name you want to assign it.
  • After writing your function in the script editor, you can call it using the format yourfunction(inputvalue1, inputvalue2, inputvalueN ).
  • Adding comments to your script makes it easy for anyone to understand the purpose of each input.

Step 1 Open up MATHWORKS MATLAB and press the New Script button.

Community Q&A

Community Answer

  • Do not forget the semicolon when defining your equation this will suppress the output which means it will not output the number before you want it to be outputted to the user Thanks Helpful 1 Not Helpful 0
  • In other programming language the new line character is "/n"; in MATLAB it is "\n". Thanks Helpful 0 Not Helpful 0
  • If you do not save your program it will not work, or when you execute or call your function nothing will happen. Thanks Helpful 0 Not Helpful 0
  • For every Matlab function you create you must add a END to it this is crucial and your program will not work otherwise. Thanks Helpful 0 Not Helpful 0

You Might Also Like

Import, Graph, and Label Excel Data in MATLAB

About This Article

  • Send fan mail to authors

Is this article up to date?

write matlab program

Featured Articles

Study Efficiently

Trending Articles

How to Take the Perfect Thirst Trap

Watch Articles

Wrap a Round Gift

  • Terms of Use
  • Privacy Policy
  • Do Not Sell or Share My Info
  • Not Selling Info

wikiHow Tech Help Pro:

Level up your tech skills and stay ahead of the curve

  • Free MATLAB Certification
  • Privacy Policy
  • Latest update and News
  • Join Us on Telegram
  • 100 Days Challenge

MATLAB Programming

Search This Blog

  • 100 Days Challenge (97)
  • Accelerometer (2)
  • Acoustic wave (1)
  • Add-Ons (1)
  • AlexNet (2)
  • Algorithms (13)
  • Amplitude Demodulation (1)
  • Amplitude Modulation (3)
  • Android (4)
  • Animation (3)
  • Antenna Design (6)
  • App Design (14)
  • Applications (6)
  • Arduino (18)
  • Automorphic Number (1)
  • Autonomous Driving (4)
  • Autonomous Navigation (7)
  • Autosar (8)
  • Battery (21)
  • Big Data (1)
  • Blockset (15)
  • Bluetooth (3)
  • Bode Plot (1)
  • Boundary Conditions (1)
  • Bubble Sort (1)
  • Buck Converter (3)
  • CAN Bus (2)
  • Castor Classes (6)
  • Circles (3)
  • Clustering (3)
  • Code Generation (3)
  • Computer Vision (21)
  • Control (21)
  • Control Systems (13)
  • Correlation (10)
  • Course (20)
  • Creativity (1)
  • Cryptography (1)
  • CubeSat (1)
  • Curve Fitting (2)
  • Data Analysis (38)
  • Data Science (21)
  • Data Set (2)
  • Dataflow (2)
  • Deep Learning (68)
  • Demodulation (3)
  • Differential Equations (2)
  • Digital Communication (16)
  • Digital Twins (2)
  • Dijkstra's Algorithm (1)
  • DO-178C (1)
  • Downloads (35)
  • Dr. Ajay Verma (16)
  • Drilling Systems Modeling & Automation (8)
  • DSP by Po Chen (2)
  • DSP by Satadru Mukherjee (48)
  • Electrical (1)
  • Electronics (50)
  • Electronics/Electrical Simulink (4)
  • Embedded (12)
  • Face Detection (4)
  • Fault Detection and Diagnosis in Chemical and Petrochemical Processes (3)
  • Femur; Mechanical properties; Finite element; MATLAB environment (1)
  • Filter (14)
  • Finance (2)
  • Floor function (1)
  • Fourier Transform (3)
  • Frequency Modulation (1)
  • Frequency Plotting (2)
  • Fuel Cells (1)
  • Genetic Algorithm (9)
  • Graphics (3)
  • Heat Transfer (3)
  • Histogram (1)
  • Image Processing (133)
  • Importing Data (1)
  • Induction Motor (1)
  • Interface (1)
  • Interpolation (6)
  • Interview Questions (4)
  • Jupyter Notebook (1)
  • K-Means Clustering (5)
  • Kalman Filter (9)
  • Line Detection (1)
  • Line Styles (1)
  • Live Editor (7)
  • Lookup Tables (2)
  • Machine Learning (80)
  • Manchester Line (1)
  • Mapping Toolbox (2)
  • Mathematics (119)
  • MATLAB & JAVA (25)
  • MATLAB BASICS (154)
  • MATLAB Books (172)
  • MATLAB Codes (84)
  • MATLAB Command (6)
  • MATLAB EXPO (2)
  • MATLAB for Beginners (75)
  • MATLAB FOR ENGINEERS (30)
  • MATLAB FUN (36)
  • MATLAB Functions (31)
  • MATLAB Mobile (1)
  • MATLAB Program for beginners (71)
  • MATLAB PROGRAMS (205)
  • MATLAB Project (10)
  • MATLAB Simscape (39)
  • MATLAB Simulink (204)
  • MATLAB Software (101)
  • MATLAB Videos (276)
  • Mechanical (10)
  • Medical (1)
  • Mike Fitzpatrick (48)
  • Minimization (1)
  • Model Predictive Control (9)
  • Model Slicer (3)
  • Model-Based Design (1)
  • Modeling (49)
  • Modulation (8)
  • Motor Control (12)
  • Multivariate Analysis (1)
  • Nanocrystals (1)
  • Navigation Toolbox (1)
  • Neural Networks (9)
  • Newmark (1)
  • Notch Filter (1)
  • NPTEL Lectures (41)
  • NRZ Bipolar (1)
  • NRZ Polar (1)
  • NRZ Unipolar (1)
  • Numerical Analysis (4)
  • Object Detection (6)
  • object-oriented programming (1)
  • Optimization (15)
  • Pattern Recognition (1)
  • Photovoltaic (2)
  • Physical Modeling (11)
  • PID Controller (16)
  • PN Sequence (1)
  • Polar Codes (1)
  • Polynomial Regression in MATLAB (3)
  • Predictive Maintenance (12)
  • Process Monitoring (1)
  • Projects (14)
  • Q&A (2)
  • Quadcopter (1)
  • Quantum Mechanics (1)
  • Raspberry Pi (7)
  • RavenPack Analytics (RPA) (1)
  • Real Time (1)
  • Reds Library (34)
  • Regression (13)
  • Reinforcement (10)
  • RF Signal (8)
  • RoadRunner (9)
  • Robotics (38)
  • Robust Control (4)
  • ROS Toolbox (3)
  • Rotational Matrix (2)
  • Satadru Mukherjee (31)
  • Satellite (3)
  • Scientists (5)
  • Sensor Fusion (8)
  • Serial Communication (1)
  • Signal Coding (11)
  • Signal Processing (11)
  • SimBiology (5)
  • Simulations (28)
  • Simulink Coverage (1)
  • Simulink Tutorial (57)
  • Sin Wave (5)
  • Solar Inverter Control with Simulink (4)
  • Spring-Mass (1)
  • Square Wave (1)
  • State Space (4)
  • Stateflow (10)
  • Statistics (1)
  • Still Image (1)
  • Supervised Learning MATLAB (1)
  • Swarm Optimization (1)
  • Systems Engineering (8)
  • Teaching (1)
  • Tensor Flow (2)
  • Testing (2)
  • Thermal (2)
  • Toolboxes (42)
  • Transform (3)
  • Transformer (1)
  • Transmission Line (1)
  • Turbo Coding (1)
  • Validation (3)
  • Vehicle Dynamics (14)
  • Video Compression (2)
  • Vision Sensors (1)
  • Voggle's (2)
  • Wave Generation (7)
  • Waveform (9)
  • Wavelet (7)
  • Web App Server (2)
  • Workspaces (1)
  • Z-Transform (1)
  • How to Write a MATLAB Program - MATLAB Tutorial

How to Write a MATLAB Program - MATLAB Tutorial

No comments

Popular posts.

' border=

Social Counter

  • telegram count=599k; Follow
  • facebook count=725k; Follow
  • twitter count=5.7k; Follow
  • youtube count=985k; Follow
  • MATLAB Free Courses

write matlab program

  • Estimate Battery SOC With Deep Learning
  • What Is 3-Phase Power?
  • Motor Control using MATLAB
  • PID Control
  • Assignment Help

Free Courses

write matlab program

Free Certification Course

  • Advanced Linear Continuous Control Systems: Applications with MATLAB Programming and Simulink
  • Certification on MATLAB and Octave for Beginners

MATLAB/SIMULINK Course

  • MATLAB complete course by by Fitzpatrick and Ledeczi in English
  • MATLAB Programming from Basics in ENGLISH
  • SimuLink Tutorial
  • Learn MATLAB Simulink step by step
  • MATLAB/SIMULINK Complete course in HINDI/URDU
  • How to Develop Battery Management Systems in Simulink
  • Data Science Complete Course using MATLAB

Electronics and Electrical

  • Design Motor Controllers with Simscape Electrical
  • How to Develop Battery Management Systems in Simul...
  • Battery Management using MATLAB
  • Motor Drives
  • DC DC Converter
  • Control Systems in Practice

Install MATLAB 2019a for Windows PC | Full Crack Version - 2019

  • Electronics/Electrical Books using MATLAB
  • MATLAB Books PDF downloads
  • Physics Books using MATLAB

' border=

Featured post

Phase noise: under the hood | modeling plls using mixed-signal blockset.

 This is the sixth video in the Modeling PLLs Using Mixed Signal Blockset™ series and it takes a deeper dive into phase-noise modeling. Go u...

write matlab program

  • Autonomous Navigation
  • Dr. Ajay Verma
  • 100 Days Challenge- MATLAB

write matlab program

  • Interpolation and Curve Fitting in MATLAB
  • Practical Genetic Algorithms in MATLAB

Trending Technology

  • Machine Learning
  • Computer Vision
  • Artificial Intelligence
  • Deep Learning
  • Data Analysis
  • Reinforcement Learning for Engineers
  • Applied Machine Learning using MATLAB
  • Deep Learning for Engineers

Recent Updates

' border=

  • Audio Processing
  • Signal Processing
  • Video Processing

Blog Archive

  • ►  January (15)
  • ►  December (19)
  • ►  November (15)
  • ►  October (9)
  • ►  September (24)
  • ►  July (7)
  • ►  June (16)
  • ►  May (16)
  • ►  April (15)
  • ►  March (15)
  • ►  January (16)
  • ►  December (10)
  • ►  November (20)
  • ►  August (3)
  • ►  July (12)
  • ►  May (10)
  • ►  April (16)
  • ►  March (9)
  • ►  January (12)
  • ►  December (29)
  • ►  November (53)
  • ►  October (39)
  • ►  August (16)
  • ►  July (19)
  • ►  June (21)
  • ►  May (48)
  • ►  April (25)
  • ►  March (26)
  • ►  February (23)
  • ►  December (18)
  • ►  November (19)
  • ►  October (31)
  • ►  September (16)
  • ►  August (36)
  • ►  July (72)
  • ►  June (71)
  • ►  May (190)
  • ►  April (137)
  • ►  March (171)
  • ►  February (41)
  • ►  January (63)
  • ►  December (50)
  • ►  November (81)
  • ►  October (162)
  • ►  September (47)
  • ►  August (43)
  • ►  July (48)
  • ►  June (68)
  • ►  May (46)
  • ►  April (30)
  • ►  March (42)
  • ►  February (55)
  • ►  January (58)
  • ►  December (78)
  • Spiral cone in MATLAB (no built in function)
  • MATLAB Program for Hypnotic Spiral Vector Image
  • Video Processing in MATLAB
  • Data Analysis with MATLAB for Excel Users
  • MATLAB for New Users
  • Linear convolution using Circular convolution(With...
  • How to Create a GUI with GUIDE - MATLAB Tutorial
  • Circular shift in MATLAB(with and without built in...
  • Example 2 on circular convolution in MATLAB
  • Circular Convolution using MATLAB
  • Inverse FFT(DFT) in MATLAB
  • Discrete Fourier Transform in MATLAB
  • FAST FOURIER TRANSFORM in MATLAB
  • Numerical Problem on DTFT using MATLAB
  • Discrete Time fourier transform in MATLAB|PART 3
  • Discrete Time Fourier Transform in MATLAB|Part 2
  • Discrete Time Fourier Transformation in MATLAB|PART 1
  • Signal Energy in MATLAB
  • Numerical on Random sequences generation in MATLAB
  • Random Sequence generation in MATLAB | PART 2
  • Random sequence Generation in MATLAB | Part 1
  • Realization of "Addition" in MATLAB with example
  • Plot a unit circle using sine and cosine functions...
  • Realization of a periodic Signal in MATLAB
  • Signum function in MATLAB | m-file
  • Numerical questions on Digital Signal Processing |...
  • Complex Exponential Signal in MATLAB | M-file
  • Real Exponential Signal in MATLAB | M-file
  • Sine and cos signal in MATLAB | m-file
  • Unit Ramp Signal in MATLAB
  • MATLAB code for Unit impulse signal from unit step...
  • MATLAB Program for Dicrete Unit Impulse Function
  • WLAN Simulation Using MATLAB
  • LTE Simulation using MATLAB
  • 5G Simulation using MATLAB
  • Real Time Motor Model for HIL Testing using MATLAB
  • Ordinary and Partial Differential Equation Routine...
  • MATLAB: What Is Machine Learning?
  • Battery Data Acquisition and Analysis Using MATLAB
  • Hardware and Software Co Design for Motor Control ...
  • Optical Scanning Holography with MATLAB (R) by Ti...
  • Numerical Techniques for Chemical and Biological E...
  • Numerical Methods Using Matlab by Mathews and Fink
  • ►  October (68)
  • ►  September (9)
  • ►  August (17)
  • ►  July (25)
  • ►  June (17)
  • ►  May (5)
  • ►  April (6)
  • ►  March (4)
  • ►  October (5)
  • ►  September (1)
  • Join Us on Telegram with 10k people
  • MATLAB Software
  • MATLAB Books

write matlab program

MATLAB Programs/Code (matlabcoding.com)

Subscribe To

' border=

write matlab program

  • Testimonials

2020 All Rights Reserved By © Matlab Simulation

Form Submitted

Www.matlabsimulation.com, matlab programming examples, related pages.

Matlab Coding Help

Thesis Matlab Code

Matlab Project Help

Small Matlab Projects

Matlab Online Support

Matlab Program Example

Simple Matlab Projects

Matlab Simulation Help

Thesis With Matlab Code

Matlab Gui Project Ideas

Matlab Dissertation Topics

Student Matlab Projects

Matlab Programs Online Help

Source Code For Matlab Projects

Simple Matlab Projects For Students

Research Areas

Digital Image processing

Medical Image processing

Biomedical Signal processing

Biometric Detection

Information Security

Neural Networks

Network Security

Wireless Networks

Wireless Communication

Matlab Simulink

power Electronics

Renewable Energy

Mobile Communication

Satellite Communication

Optical Communication

Video processing

Artificial Intelligence

Advanced Robotics

Related Tools

3D-2D CONVERTER

RAPID MINER

SENTI WORDNET

CLOUD REPORTS

Matlab Programming Examples give you a brief overview of Matlab programs. Generally, Matlab programming can be done using object-oriented programming, GUI programming, and basic Matlab syntax and functions. Students must be aware of Matlab programming in order to implement a complete project in Matlab. We are also working with Matlab for the past ten years. We have worked on every version of Matlab, including the latest version (R2016a). Taking a project in Matlab is the best way to learn Matlab programming. We can offer matlab programming examples for you from thousands of projects as we have developed nearly 5000+ projects in Matlab. If you need any programs or projects in Matlab, mail us your requirements, we will give you your required code.

   Our  Matlab Programming Examples  gives a brief knowledge about Matlab programming basics. To learn about Matlab programming, the basics of Matlab are essential. We have enumerated below, few example programs on functions, graphics, and arithmetic functions. These all are basic Matlab concepts that one has to know before taking complex programs. We also support advanced and complex programs in Matlab for students who aid in our help. We have a solution for every problem.

Matlab Functions

   In general, Matlab functions are used to create all major applications in Matlab. All the functions are written in a file and saved as “filename.m.” All Matlab programs are written using m-files having an extension of “.m.” M-files are of two types, namely script files and script function files. New functions can also be created by merging existing functions. Function files have both input and output arguments. In short, it behaves like FORTRAN subroutines or C functions.

Basic Syntax

Function outputs =my_fun(inputs)

Sample Program For Functions

Function y= my_fun(x)

y=x.sin(3*x.^2).*exp(-x.^2/4)

Square Matrix Construction Using Functions

function B=inv_sq(A)

if abs(det(A)) <0.0001,

error(‘The matrix is singular’)

B=inv(A^2);

Mathematical Function Example

To solve also the equation ( x=cos x).

% Sample program for functional iteration for script m-files:

% Anything following a percent sign is a comment

X=zeros (2, 1); %   Approximate solutions stored in vector x

%   Initially it is set to be a 2-by-1 vector of zeros.

X(1) =xguess   %  Initial guess goes in X(1)

for n=1: itmax   %beginning of loop

x(n+1) = .5*cos(x(n));

diff = abs(x(n+1) –X(n));  % using absolute error for simplicity

if diff<tol

break % jump out of loop

end %end if clause

end % end of loop

if n < itmax %beginning of if clause

disp(“Iterations failed to coverage to prescribed tolerance.’).

end % end of if clause

x % displays the vector x

% end of sample program

Advanced Graphics In Matlab

Using Matlab, we can develop different types of graphs like 2D curves, 3D surfaces, 2D and also 3D parametric curves etc. Major graphical operations are:

  • Parametric plots
  • Merging several graphs in single window.

Advanced Matlab Programming Examples for students

Sample Program For Plotting

To plot the graph a=b 2 in the interval [-1, 1].

>> b = -1:0.1:1

>> a=b.*b

>> plot(a,b)

Note: To add more features to the above plot, use the following commands

>> title(‘Graph of a=b^2’)

>> blabel(‘b’)

>> alabel(‘a’)

Arithmetic Operations In Matlab

In Matlab, Arithmetic operations can also performed on matrices and images. It includes addition, subtraction and also multiplications. In addition to it, it works on standard operations, vectorized functions and also operators, matrix equations using matrix division etc. Let’s take an Example of Image Arithmetic also to understand about Matlab arithmetic operations.

Image Arithmetic In MATLAB With Example

Generally, an image is represented in the form of Matrix. To perform Image arithmetic between two images, the size of two images must be same and also it result in a new image. Let the two images be X and also Y with same size:

Input image: RGB image

Z=X+Y (minimum value of X+Y is 255)   // Image Addition

i.e. Z(a,b,1)=min(X(a,b,1)+Y(a,b,1),255) // where (a,b) represents the pixel position.

Z=X-Y (maximum value of X-Y is 0)        // Image Subtraction

i.e. Z(a,b,:)=max(X(a,b,:)+Y(a,b,:),0)

Z=X.*Y;           // Image multiplication

Z=X.\Y;          // Image division

Logical Operations On Image

It is performed on pixel by pixel basis. Logical AND and also OR operations are used to select a sub image from an image. This masking process is known as ROI (Region of Interest processing). Now, consider a mask image ‘L’ for a image ‘X’. To obtain the acquired area using AND operation, use the following command:

   V= and (L, X); (or) V= L&X;         

V=or (L, X); (or) V=L|X;   //For OR operation

Programming Example

background=imread(‘back_ground.jpg’);

X=imread(‘ball.bmp’);

Y=imread(‘balloon.bmp’);

object=X+Y;    %Image addition: Both X and Y are of same size

background=imresize(background,[size(object,1) size(object,2)]);

Im3=uint8(zeros(size(object)));

whiteImg=uint8(ones(size(object))); %Array right division. X./Y is the matrix with elements X(i,j)/Y(i,j). X and also Y must have the same size, unless one of them is a scalar.

mask=whiteImg./object; %Image Division %Logical AND operation

im3=uint8(mask&background);%uint8(and(mask,background));

figure,imshow(mask);

%Array multiplication. X.*Y is the element-by-element product of the arrays X and Y.

%Image multiplication

%Multiply the background and also the mask image

%And the result with the foreground image to obtain the final Image.

finalImg=(background.*im3)+object;

figure,imshow(finalImg);

A life is full of expensive thing ‘TRUST’ Our Promises

100% confidential.

We don’t disclose our client’s data to any third party and it is kept as secret to all.

Fresh Ideas

All the time, you receive only the novel ideas that not release from anywhere.

Work Guarantee

We guarantee for your satisfaction and it is not further need of correction and complaints.

Plagiarism Free

We follow our own writing. It means that without copying from any source, we write it.

We are not intent to sale our product to more than one person. It is totally new for each.

Business Ethics

Surely, we follow our set of ethics to send the high quality products for everyone.

On-Time Delivery

We always deliver your work at the time of delivery. So that feels our timely guidance.

Affordable Price

We are not serving with high cost. You get an excellent work in at reasonable price.

We meet each individual customer’s demands by our years of skills. This is the secret of success.

Great Memories Our Achievements

We received great winning awards for our research awesomeness and it is the mark of our success stories. It shows our key strength and improvements in all research directions.

write matlab program

Our Guidance

  • Assignments
  • Literature Survey
  • Mathematical Proofs
  • Research Proposal
  • System Development
  • Paper Writing
  • Conference Paper
  • Thesis Writing
  • Dissertation Writing
  • Hardware Integration
  • Paper Publication

24/7 Support, Call Us @ Any Time [email protected] +91 94448 56435

  • MATLAB Answers
  • File Exchange
  • Ask a question
  • Answer questions
  • Upload files
  • Connect to GitHub
  • Share a link
  • Solve Cody problems
  • Communities
  • Treasure Hunt
  • Community Advisors
  • Virtual Badges
  • Community Home
  • Discussions
  • AI Chat Playground

Cleve’s Corner: Cleve Moler on Mathematics and Computing

Nick Higham (1961-2024)

The MATLAB Blog

Producing animated gifs from MATLAB Flipbook Mini Hack entries

Steve on Image Processing with MATLAB

An Example of Function Argument Validation for an Image Utility Function

Guy on Simulink

Become a MathWorks Certified Simulink Associate!

Artificial Intelligence

Verification and Validation for AI: Learning process verification

Developer Zone

Dependency-based Test Selection

Stuart’s MATLAB Videos

Calculating the Duration of an Animated GIF file

Behind the Headlines

Three favorites from TIME Magazine’s “Best Innovations of 2023”

File Exchange Pick of the Week

Statistical visualization functions and “Open in MATLAB Online”

Hans on IoT

An interview with MATLAB playground: Build your IoT Analysis and Plots for ThingSpeak

Student Lounge

Climb stairs and shoot the target: A Student Robotics Project!

MATLAB Community

Newton’s Method Fractals

MATLAB ユーザーコミュニティー

MATLAB で大規模言語モデル

Startups, Accelerators, & Entrepreneurs

Startup Spotlight: Olympian Motors is Bringing a New Fleet of EVs to the Streets

Autonomous Systems

🤖💡 Making Remote Robot Software Updates a Breeze: Discover the Power of ROS Toolbox & Automated Tools

Quantitative Finance

Deep Learning in Quantitative Finance: Transformer Networks for Time Series Prediction

MATLAB Graphics and App Building

Creating a Flight Tracking Dashboard, Part 1: Visualizing an Aircraft

  • Posts (feed)

bio_img_matlab

Mike Croucher is a Customer Success Engineer for Research and Education who previously spent 20 years working in academic research computing. He writes about MATLAB, MathWorks, and intersections with other technologies for those who are changing the world.

The MATLAB Blog Practical Advice for People on the Leading Edge

Using ai to help write matlab code – the matlab ai chat playground.

Posted by Mike Croucher , November 15, 2023

Stage 1: I hate it and I can’t trust it.

Stage 2: well…this is kind of fun.

write matlab program

Stage 3: Getting practice by using AI in low-stakes situations

Stage 4: using ai for real work, over to you, you are now following this blog post.

You will see updates in your activity feed .

You may receive emails, depending on your notification preferences .

print

MATLAB Virtual Conference - "the high point of geekism this year"

write matlab program

New AI Examples in R2022b

A chess coach encounters the "300 dpi" mystery.

write matlab program

Staker v0.6

write matlab program

Pacman (with a twist)!

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.

  • DSA Tutorial
  • Data Structures
  • Linked List
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Divide & Conquer
  • Mathematical
  • Backtracking
  • Branch and Bound
  • Pattern Searching

Related Articles

  • Solve Coding Problems
  • Single Side Band (SSB) Modulation and Demodulation using MATLAB
  • User defined function in MATLAB
  • Information Entropy using MATLAB
  • Uniquely Decodable Code using MATLAB
  • Root Locus using MATLAB
  • How to vertically flip an Image using MATLAB
  • Up-sampling in MATLAB
  • Solution of system of linear equation in MATLAB
  • NumPy for Matlab users
  • Comments in MATLAB
  • Arithmetic Encoding and Decoding Using MATLAB
  • Down-sampling in MATLAB
  • Linear Block Code using MATLAB
  • Steady State Model using MATLAB
  • Frequency Modulation (FM) using MATLAB
  • How to Extract Frames From a Video in MATLAB?
  • MATLAB - Loops
  • Edge detection using in-built function in MATLAB
  • MATLAB - Image Edge Detection using Sobel Operator from Scratch

Simple Input/Output Program in MATLAB

Syntax : input(PROMPT, “s”) Parameters : PROMPT : text prompted “s” : optional, to input a string Returns : the data entered
Syntax : display(OBJ) Parameters : OBJ : the object to be displayed Returns : Nothing

Please Login to comment...

  • Competitive Programming
  • Computer Subject

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Help Center Help Center

  • Help Center
  • Trial Software
  • Product Updates
  • Documentation

Write data to text file

Description

fprintf( fileID , formatSpec , A1,...,An ) applies the formatSpec to all elements of arrays A1,...An in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen .

fprintf( formatSpec , A1,...,An ) formats data and displays the results on the screen.

nbytes = fprintf( ___ ) returns the number of bytes that fprintf writes, using any of the input arguments in the preceding syntaxes.

collapse all

Print Literal Text and Array Values

Print multiple numeric values and literal text to the screen.

%4.2f in the formatSpec input specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point. %8.3f in the formatSpec input specifies that the second value in each line of output is a floating-point number with a field width of eight digits, including three digits after the decimal point. \n is a control character that starts a new line.

Print Double-Precision Values as Integers

Explicitly convert double-precision values with fractions to integer values.

%d in the formatSpec input prints each value in the vector, round(a) , as a signed integer. \n is a control character that starts a new line.

Write Tabular Data to Text File

Write a short table of the exponential function to a text file called exp.txt .

The first call to fprintf prints header text x and exp(x) , and the second call prints the values from variable A .

If you plan to read the file with Microsoft ® Notepad , use '\r\n' instead of '\n' to move to a new line. For example, replace the calls to fprintf with the following:

MATLAB ® import functions, all UNIX ® applications, and Microsoft Word and WordPad recognize '\n' as a newline indicator.

View the contents of the file with the type command.

Get Number of Bytes Written to File

Write data to a file and return the number of bytes written.

Write an array of data, A , to a file and get the number of bytes that fprintf writes.

The fprintf function wrote 96 bytes to the file.

Close the file.

Display Hyperlinks in Command Window

Display a hyperlink ( The MathWorks Web Site ) on the screen.

%s in the formatSpec input indicates that the values of the variables url and sitename , should be printed as text.

Input Arguments

Fileid — file identifier 1 (default) | 2 | scalar.

File identifier, specified as one of the following:

A file identifier obtained from fopen .

1 for standard output (the screen).

2 for standard error.

Data Types: double

formatSpec — Format of output fields formatting operators

Format of the output fields, specified using formatting operators. formatSpec also can include ordinary text and special characters.

If formatSpec includes literal text representing escape characters, such as \n , then fprintf translates the escape characters.

formatSpec can be a character vector in single quotes, or a string scalar.

Formatting Operator

A formatting operator starts with a percent sign, % , and ends with a conversion character. The conversion character is required. Optionally, you can specify identifier, flags, field width, precision, and subtype operators between % and the conversion character. (Spaces are invalid between operators and are shown here only for readability).

Schematic of formatting operator characters.

Conversion Character

This table shows conversion characters to format numeric and character data as text.

Optional Operators

The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.

Order for processing the function input arguments. Use the syntax n $ , where n represents the positions of the other input arguments in the function call.

Example: ('%3$s %2$s %1$s %2$s','A','B','C') prints input arguments 'A' , 'B' , 'C' as follows: C B A B .

Note: If an input argument is an array, you cannot use identifiers to specify particular array elements from that input argument.

Field Width

Minimum number of characters to print. The field width operator can be a number, or an asterisk ( * ) to refer to an input argument.

When you specify * as the field width operator, the other input arguments must provide both a width and a value to be printed. Widths and values can be pairs of arguments or pairs within a numeric array. With * as the field width operator, you can print different values with different widths.

Example: The input arguments ('%12d',intmax) are equivalent to ('%*d',12,intmax) .

Example: The input arguments ('%*d',[2 10 5 100]) return '10 100' , with two spaces allocated for 10 and five spaces for 100 . As an alternative, you also can specify the field widths and values as multiple arguments, as in ('%*d',2,10,5,100) .

The function pads to field width with spaces before the value unless otherwise specified by flags.

The precision operator can be a number, or an asterisk ( * ) to refer to an argument.

When you specify * as the field precision operator, the other input arguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array. With * as the precision operator, you can print different values to different precisions.

When you specify *.* as field width and precision operators, you must specify field widths, precisions, and values as triplets.

Example: The input arguments ('%.4f',pi) are equivalent to ('%.*f',4,pi) .

Example: The input arguments ('%6.4f',pi) are equivalent to ('%*.*f',6,4,pi) .

Example: The input arguments ('%*.*f',6,4,pi,9,6,exp(1)) return '3.1416 2.718282' , with 9 and 6 as the field width and precision for the output of exp(1) .

If you specify a precision operator for floating-point values that exceeds the precision of the input numeric data type, the results might not match the input values to the precision you specified. The result depends on your computer hardware and operating system.

You can use a subtype operator to print a floating-point value as its octal, decimal, or hexadecimal value. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.

Text Before or After Formatting Operators

formatSpec can also include additional text before a percent sign, % , or after a conversion character. The text can be:

Ordinary text to print.

Special characters that you cannot enter as ordinary text. This table shows how to represent special characters in formatSpec .

Notable Behavior of Conversions with Formatting Operators

Numeric conversions print only the real component of complex numbers.

If you specify a conversion that does not fit the data, such as a text conversion for a numeric value, MATLAB overrides the specified conversion, and uses %e .

Example: '%s' converts pi to 3.141593e+00 .

If you apply a text conversion (either %c or %s ) to integer values, MATLAB converts values that correspond to valid character codes to characters.

Example: '%s' converts [65 66 67] to ABC .

A1,...,An — Numeric or character arrays scalar | vector | matrix | multidimensional array

Numeric or character arrays, specified as a scalar, vector, matrix, or multidimensional array.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

Output Arguments

Nbytes — number of bytes scalar.

Number of bytes that fprintf writes, returned as a scalar. When writing to a file, nbytes is determined by the character encoding. When printing data to the screen, nbytes is the number of characters displayed on the screen.

Format specifiers for the reading functions sscanf and fscanf differ from the formats for the writing functions sprintf and fprintf . The reading functions do not support a precision field. The width field specifies a minimum for writing, but a maximum for reading.

If you specify an invalid formatting operator or special character, then fprintf prints all text up to the invalid operator or character and discards the rest.

Example: If formatSpec is 'value = %z' , then fprintf prints 'value =' because %z is not a formatting operator.

Example: If formatSpec is 'character \x99999 = %s' , then fprintf prints 'character' because \x99999 is not a valid special character.

[1] Kernighan, B. W., and D. M. Ritchie, The C Programming Language , Second Edition, Prentice-Hall, Inc., 1988.

[2] ANSI specification X3.159-1989: “Programming Language C,” ANSI, 1430 Broadway, New York, NY 10018.

Extended Capabilities

C/c++ code generation generate c and c++ code using matlab® coder™..

Usage notes and limitations:

The formatSpec parameter must be constant.

In formatSpec , hexadecimal numbers must be in the range [0 7F] and octal numbers must be in the range [0 177].

If fileID has a constant value of 1 or 2 and extrinsic calls are not possible, the code generator produces a C printf call. Extrinsic calls are not possible when extrinsic calls are disabled or when fprintf is called inside a parfor loop.

The behavior of fprintf in the generated code matches the C compiler behavior instead of the MATLAB behavior in these cases:

The format specifier has a corresponding C format specifier, for example, %e or %E .

The fprintf call is inside a parfor loop.

Extrinsic calls are disabled.

These options and capabilities are not supported:

The n$ position identifier for reordering input values

Printing arrays

Using subtypes to print a floating-point number as its octal, decimal, or hexadecimal value

When you call fprintf with the format specifier %s , you cannot put a null character in the middle of the input character vector. To write a null character, use fprintf(fid, '%c', char(0)) .

Input argument types must match their format types. For example, if n is a double, code generation does not allow the following code: str = sprintf( '%d' ,n)

For code generation, first cast n to a signed integer type such as int8 . str = sprintf( '%d' ,int8(n))

When you call fprintf with an integer format specifier, the type of the integer argument must be a type that the target hardware can represent as a native C type. For example, if you call fprintf('%d', int64(n)) , then the target hardware must have a native C type that supports a 64-bit integer.

Thread-Based Environment Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment .

GPU Arrays Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

This function accepts GPU arrays, but does not run on a GPU.

For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox) .

Distributed Arrays Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.

This function operates on distributed arrays, but executes in the client MATLAB.

For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox) .

Version History

Introduced before R2006a

disp | fclose | ferror | fopen | fread | fscanf | fwrite | fseek | ftell | sprintf

  • Export Cell Array to Text File
  • Append to or Overwrite Existing Text Files
  • Formatting Text

Open Example

You have a modified version of this example. Do you want to open this example with your edits?

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

  • Switzerland (English)
  • Switzerland (Deutsch)
  • Switzerland (Français)
  • 中国 (English)

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

  • América Latina (Español)
  • Canada (English)
  • United States (English)
  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)

Contact your local office

  • Python Programming
  • C Programming
  • Numerical Methods
  • Dart Language
  • Computer Basics
  • Deep Learning
  • C Programming Examples
  • Python Programming Examples

Bisection Method MATLAB Program with Output

Table of Contents

  • MATLAB Program
  • Program Output

Recommended Readings

This program implements bisection method for finding real root of nonlinear equation in matlab..

In this MATLAB program, y is nonlinear function, a & b are two initial guesses and e is tolerable error.

MATLAB Source Code: Bisection Method

Bisection method matlab output.

  • Bisection Method Algorithm
  • Bisection Method Pseudocode
  • Python Program for Bisection Method
  • C Program for Bisection Method
  • C++ Program for Bisection Method
  • MATLAB Program for Bisection Method
  • Bisection Method Advantages
  • Bisection Method Disadvantages
  • Bisection Method Features
  • Convergence of Bisection Method
  • Bisection Method Online Calculator

IMAGES

  1. How to write your first MATLAB program

    write matlab program

  2. MATLAB Tutorial

    write matlab program

  3. Writing a MATLAB Program

    write matlab program

  4. How to Write a MATLAB Program

    write matlab program

  5. Write a Matlab program to add all the even numbers from 0 to 100

    write matlab program

  6. write matlab program

    write matlab program

VIDEO

  1. MATLAB Basics| MATLAB Tutorial

  2. Introduction to MATLAB

  3. MATLAB Previous Version

  4. MATLAB Lecture 4: Scripts and Functions

  5. Write your first MATLAB Program

  6. MATLAB summary (While)

COMMENTS

  1. How to Write a MATLAB Program

    How to Write a MATLAB Program Write a basic MATLAB ® program using Live Scripts and learn the concepts of indexing, if-else statements, and loops. Feedback Write a basic MATLAB Program using Live Scripts and learn the concepts of indexing, if-else statements, and loops.

  2. Programming with MATLAB

    MATLAB is a high-level programming language designed for engineers and scientists that expresses matrix and array mathematics directly. You can use MATLAB for everything, from running simple interactive commands to developing large-scale applications. Start Simple—No Programming Experience Required

  3. Programming and Scripts

    The simplest type of MATLAB ® program is called a script. A script is a file that contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line. Scripts To create a script, use the edit command, edit mysphere This command opens a blank file named mysphere.m.

  4. PDF Basic Examples for Matlab

    Write your first Matlab program Ex. 1 Write your first Matlab program = 3; = 5; = a+b Output: 8 Remarks: (1) The semicolon at the end of a statement acts to suppress output (to keep the program running in a "quiet mode"). (2) The third statement, c = a+b, is not followed by a semicolon so the content of the variable c is "dumped" as the output.

  5. How to Write a MATLAB Program

    Captions available in french and spanish. Learn how to write a basic MATLAB program using Live Scripts and learn the concepts of indexing, if-else statements...

  6. Writing a MATLAB Program

    654 241K views 10 years ago Write a MATLAB program, including creating a script and a function. Get a Free MATLAB Trial: https://goo.gl/C2Y9A5 Learn MATLAB for free: https://goo.gl/xIiHyG...

  7. Writing Your First Program

    Start writing a new program by clicking new script at the top left of the Matlab window It is always wise to place some notes at the top of your program describing the programs purpose. It is also a good idea to place comments around confusing parts of your code.

  8. How to Write a Function and Call It in MATLAB: 12 Steps

    1 Open up MATHWORKS MATLAB and press the New Script button. This button will be on the upper left side of your screen. 2 Type your function name. The name of your function should be the name of your file, so when you save this new script file it will be the name of your file. In this case, for example, you can name our function slope-equation. 3

  9. MATLAB: Getting Started on Writing Code for Beginners

    How to get started in writing code in MATLAB. Script files (.m)How to Create Programs in MATLAB tutorial playlist: https://youtube.com/playlist?list=PLmB_c16...

  10. How to Write a MATLAB Program

    How to Write a MATLAB Program - MATLAB Tutorial. Learn how to write a basic MATLAB program using Live Scripts and learn the concepts of indexing, if-else statements, and loops.

  11. PDF Writing Programs in MATLAB

    Writing Programs in MATLAB MATLAB program is a file containing a list of MATLAB commands that are executed in a particular sequence. In MATLAB, a program file name must end with the extension ".m", called an M-file. To run a program, type the file name (without the ".m" extension) at the MATLAB prompt.

  12. Matlab Programming Examples for Beginners

    All Matlab programs are written using m-files having an extension of ".m." M-files are of two types, namely script files and script function files. New functions can also be created by merging existing functions. Function files have both input and output arguments. In short, it behaves like FORTRAN subroutines or C functions. Basic Syntax

  13. Get Started with MATLAB

    Desktop Basics Enter statements at the command line and view results. Matrices and Arrays MATLAB operates primarily on arrays and matrices, both in whole and in part. A matrix is a two-dimensional array often used for linear algebra. Array Indexing Variables in MATLAB are typically arrays that can hold many numbers.

  14. Introduction to MATLAB

    Writing a MATLAB program: Using Command Window: Only one statement can be typed and executed at a time. It executes the statement when the enter key is pressed. This is mostly used for simple calculations. Note: ans is a default variable created by MATLAB that stores the output of the given computation.

  15. PDF Programing the Finite Element Method with Matlab

    Programing the Finite Element Method with Matlab. Jack Chessa 3rd October 2002. 1 Introduction. The goal of this document is to give a very brief overview and direction in the writing of nite element code using Matlab. It is assumed that the reader has a basic familiarity with the theory of the nite element method, and our attention will be ...

  16. Using AI to help write MATLAB code

    Using AI to help write MATLAB code - The MATLAB AI Chat Playground Posted by Mike Croucher, November 15, 2023 1067 views (last 30 days) | 0 Likes | 0 comment Along with almost everyone who works in software development, I've recently been exploring how to integrate AI systems in my day-to-day work.

  17. Convolution in Matlab With Code Examples

    Demonstrate the necessary components of the code used to perform convolution in Matlab in a simplified manner. Visualize the results by plotting graphs of convoluted functions. This Tutorial is arranged in the following sequence:

  18. Basic Matrix Operations

    Trial Software Product Updates Basic Matrix Operations This example shows basic techniques and functions for working with matrices in the MATLAB® language. First, let's create a simple vector with 9 elements called a. a = [1 2 3 4 6 4 3 4 5] a = 1×9 1 2 3 4 6 4 3 4 5

  19. Declare function name, inputs, and outputs

    Description example function [y1,...,yN] = myfun (x1,...,xM) declares a function named myfun that accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

  20. Regula Falsi (False Position) Method Using MATLAB

    MATLAB program for finding real root of non-linear equation using Regula Falsi Method with Output. Regula Falsi method is also known as False Position Method. In this MATLAB program for false position method, y is nonlinear function, a & b are two initial guesses and e is tolerable error. MATLAB Source Code: Regula Falsi Method

  21. Simple Input/Output Program in MATLAB

    Parameters : PROMPT : text prompted. "s" : optional, to input a string. Returns : the data entered. The input () function is used to input data in MATLAB. Example : % entering an integer. input ("Enter an integer : ") % entering a string.

  22. Answered: Discussion Write a MATLAB program to…

    Discussion Write a MATLAB program to find the Trigonometric Fourier Series and Complex Exponential Fourier Series of the following periodic signal: Amplitude 1.5 1 0.5 0 -0.5 -1 -1.5 N М 0 Time. BUY. Introductory Circuit Analysis (13th Edition) 13th Edition. ISBN: 9780133923605.

  23. Write data to text file

    Description example fprintf (fileID,formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen. example fprintf (formatSpec,A1,...,An) formats data and displays the results on the screen. example

  24. Bisection Method MATLAB Program with Output

    Bisection Method MATLAB Output. Enter non-linear equations: cos (x) - x * exp (x) Enter first guess: 0 Enter second guess: 1 Tolerable error: 0.00001 a b c f (c) 0.000000 1.000000 0.500000 0.053222 0.500000 1.000000 0.750000 -0.856061 0.500000 0.750000 0.625000 -0.356691 0.500000 0.625000 0.562500 -0.141294 0.500000 0.562500 0.531250 -0.041512 ...