Tuesday, July 29, 2025

Using Built-in Functions

MATLABit

MATLAB stands for MATrix LABoratory. It’s a powerful programming language and software tool created by MathWorks. Its extensive application across engineering, scientific research, academic instruction, and algorithmic design stems from its strengths in numerical computation, data analysis, graphical visualization, and simulation. With a foundation in matrix algebra, MATLAB efficiently manages large datasets and complex mathematical models. Thus, we are well-positioned to commence our exploration of its capabilities. So, let's have a look on library of built-in functions.

🌸MATLAB Using Built-in Functions in Editor Window 🌸

🌸MATLAB Using Built-in Functions in Command Window 🌸

Table of Contents

Introduction

You can use built-in mathematical functions in MATLAB to improve your expressions beyond just carrying out simple arithmetic operations. This greatly increases the platform's computational power. These functions are part of MATLAB’s extensive library, designed to handle a wide range of mathematical, engineering, and scientific tasks efficiently. Usually, the arguments in parenthesis come after the name of each function. For instance, the function sqrt(x), where x is the input value and sqrt is the function name, calculates the square root of its argument x. This argument can take various forms — it may be a direct numerical value, a previously defined variable, or a more complex computable expression composed of numbers, variables, and even other functions. What makes MATLAB particularly powerful is the flexibility with which functions can be nested within one another or combined with arithmetic operations to create sophisticated mathematical expressions. This enables users to perform complex calculations in a concise and readable manner, making MATLAB a highly effective tool for both simple computations and advanced algorithm development.

Important Built-in Functions

A comprehensive collection of MATLAB functions, grouped by category, can be easily accessed through the Help Window. Below is a glimpse of some commonly used elementary mathematical functions, along with their descriptions and sample usage:

Function Description Example Result
sqrt(x) Calculates the square root of a number x. >> sqrt(49) ans = 7
nthroot(x, n) Computes the real nth root of a real number x. If x is below zero then n must be an integer with an odd value. >> nthroot(243, 5) ans = 3
exp(x) Returns the value of e raised to the power x (i.e., ex). >> exp(3) ans = 20.0855

Below is another set of commonly used elementary mathematical functions in MATLAB, each with a brief description and updated example usage:

Function Description Example Result
abs(x) Returns the absolute value of x. >> abs(-17) ans = 17
log(x) log(x) determines x's natural logarithm (base e). >> log(500) ans = 6.2146
log10(x) Computes the base 10 logarithm of x. >> log10(10000) ans = 4.0000
factorial(x) Returns the factorial of x (i.e., x!).
(x must be a non-negative integer)
>> factorial(6) ans = 720

MATLAB provides a robust set of trigonometric functions for both radian and degree inputs, enabling precise mathematical and engineering computations. Below is a refreshed table of common trigonometric functions using completely new example values:

Function Description Example Result
sin(x) Sine of angle x in radians. >> sin(pi/2) ans = 1.0000
sind(x) Sine of angle x in degrees. >> sind(90) ans = 1.0000
cos(x) Cosine of angle x in radians. >> cos(pi) ans = -1.0000
cosd(x) Cosine of angle x in degrees. >> cosd(180) ans = -1.0000
tan(x) Tangent of angle x in radians. >> tan(pi/3) ans = 1.7321
tand(x) Tangent of angle x in degrees. >> tand(60) ans = 1.7321
cot(x) Cotangent of angle x in radians. >> cot(pi/4) ans = 1.0000
cotd(x) Cotangent of angle x in degrees. >> cotd(45) ans = 1.0000

MATLAB also includes a wide range of inverse trigonometric functions used to calculate angles from given trigonometric values:

  • In radians: asin(x), acos(x), atan(x), acot(x)
  • In degrees: asind(x), acosd(x), atand(x), acotd(x)

Additionally, MATLAB supports hyperbolic trigonometric functions for advanced mathematical modeling:

  • sinh(x) – Hyperbolic sine
  • cosh(x) – Hyperbolic cosine
  • tanh(x) – Hyperbolic tangent
  • coth(x) – Hyperbolic cotangent

MATLAB provides several useful functions for rounding numbers, handling remainders, and analyzing the sign of values. Below is a refined and updated table showcasing these functions with new examples:

Function Description Example Result
round(x) Rounds x to the nearest integer. >> round(9/4) ans = 2
fix(x) Rounds x toward zero, discarding the fractional part. >> fix(-11/4) ans = -2
ceil(x) Rounds x toward positive infinity. >> ceil(7/3) ans = 3
floor(x) Rounds x toward negative infinity. >> floor(-10/3) ans = -4
rem(x, y) Returns the remainder after dividing x by y. >> rem(20, 6) ans = 2
sign(x) If x is zero, then computes zero; if x is below zero , then displays -1; and if x is above zero, then displays 1. >> sign(-12) ans = -1

Applications

Here are some practical applications of rounding and numerical functions in MATLAB, explained in simple terms:

  • 🔄 Data Cleaning & Preprocessing: Useful for simplifying raw data from sensors, user inputs, or large datasets by rounding or truncating values to make them more manageable.
  • 📊 Mathematical Modeling & Simulations: Functions like round and floor help create real-world models where precision might be limited or approximated.
  • 🖼️ Graphics & Pixel Mapping: In computer graphics, these functions convert floating-point coordinates to exact pixel positions for image processing or visual rendering.
  • 💰 Financial Calculations: Rounding methods are applied in banking or budgeting applications where decimal precision is critical — e.g., calculating taxes or payments.
  • 🤖 Control Systems & Logic Decisions: The sign function is used in robotics and automation to determine movement directions or logical paths based on input signs.
  • 🧮 Modular Arithmetic & Algorithm Design: The rem function helps in tasks like checking divisibility, identifying even/odd numbers, or developing cryptographic algorithms.

Conclusion

MATLAB Display Formats – Conclusion

  • 📌 MATLAB offers a wide range of built-in functions that make handling numbers simple, accurate, and efficient.
  • 🔢 Functions like round, floor, ceil, and fix are essential when working with real numbers that need to be approximated or adjusted.
  • ➗ The rem function helps in dividing numbers and analyzing the remainder, useful in logical and algorithmic operations.
  • ➕➖ The sign function allows you to determine the direction (positive, negative, or zero) of any value, making it a helpful tool in control logic and decision-making processes.
  • 💡 These simple yet powerful functions are building blocks in tasks such as simulations, financial computations, image processing, control systems, and more.

🧠 By mastering these elementary functions, you lay a strong foundation for performing advanced calculations and solving real-world problems efficiently using MATLAB.

© 2025 MATLABit. All rights reserved.

Thursday, July 24, 2025

Multiple Ways to Display Numbers in MATLAB

MATLABit

MATLAB stands for MATrix LABoratory. It’s a powerful programming language and software tool created by MathWorks. Its extensive application across engineering, scientific research, academic instruction, and algorithmic design stems from its strengths in numerical computation, data analysis, graphical visualization, and simulation. With a foundation in matrix algebra, MATLAB efficiently manages large datasets and complex mathematical models. Thus, we are well-positioned to commence our exploration of its capabilities. So, let's have a look on different styles of displaying numbers as needed by time.

🌸MATLAB Format Ways in Editor Window 🌸

🌸MATLAB Format Ways in Command Window 🌸

Table of Contents

Introduction

In MATLAB, users are provided with the flexibility to customize how numerical output is displayed on the screen. By dereliction, MATLAB displays numerical values in the short format, which is a fixed- point format with four integers following the decimal point. This concise display is often sufficient for general use, but MATLAB also supports a variety of alternative formats to suit different levels of precision or readability requirements. To modify the way results are shown, users can utilize the format command. This command allows the output display style to be changed dynamically during a session. Once a new format is specified using this command, all subsequent numerical output will adhere to the selected display style until it is changed again. This feature is particularly useful when working with very large or very small numbers, or when a higher degree of precision is necessary for analysis or reporting.

Multiple Displaying Styles of Numbers in MATLAB

MATLAB provides a rich set of formatting options for displaying numerical values, allowing users to tailor the appearance of output according to their specific needs—whether for readability, precision, or presentation. These display formats control only how numbers are shown in the Command Window and have no impact on the underlying computations or the way values are stored in memory. To view the complete list of supported display formats along with brief descriptions, users can simply enter the command help format in the MATLAB Command Window. This will provide a comprehensive overview, enabling more informed choices for presenting numerical results during analysis, debugging, or reporting.

MATLAB Output Display Formats Example (375 / 8)

Format Description Example Output
format short Displays numbers in fixed-point notation with 4 decimal places (default) 375 / 8 46.8750
format long Displays numbers in fixed-point notation with up to 15 decimal places 375 / 8 46.875000000000000
format short e Scientific notation with 4 digits after the decimal point 375 / 8 4.6875e+001
format long e Scientific notation with 15 digits after the decimal point 375 / 8 4.687500000000000e+001
format short g Uses the more compact of fixed-point or scientific notation with up to 5 significant digits 375 / 8 46.875
format long g Automatically switches between fixed-point and scientific format with up to 15 significant digits 375 / 8 46.875
format bank Displays values with exactly two decimal places—ideal for monetary calculations 375 / 8 46.88
format compact Minimizes blank lines in the output—provides a tighter display Affects spacing only; does not alter number format
format loose Expands output with extra blank lines—easier to read Affects spacing only; does not alter number format

Applications

The ability to control numerical display formats in MATLAB has a wide range of practical applications across different fields. In engineering and scientific research, precise output formatting is essential when interpreting results that require high numerical accuracy, such as simulations, numerical methods, and error analysis. Financial analysts often use formats like format bank to present currency data with fixed decimal places, making reports more readable and standardized. Educators and students benefit from simplified formats, such as format short or format compact, to make classroom demonstrations or assignments clearer and more concise. Additionally, when debugging complex algorithms or visualizing trends in data, switching between display formats—like scientific notation or floating-point—can offer deeper insights. Ultimately, MATLAB’s flexible formatting tools enhance both the clarity and professionalism of numerical output, making it easier to communicate results effectively across various disciplines.

Conclusion

MATLAB Display Formats – Conclusion

  • 🔢 MATLAB offers a wide range of display formats for controlling how numbers appear in the Command Window.
  • ✨ The default format, short, shows numbers with four decimal digits, but users can easily switch to formats like long, bank, or short e.
  • 🧮 These formats affect only the visual output — not how MATLAB performs internal calculations or stores data.
  • 🔬 Useful in fields like engineering, scientific computing, finance, and education for better data interpretation and presentation.
  • 📘 To explore all available options, type help format in the MATLAB Command Window.
  • 🛠️ By mastering format controls, users can make their output more precise, readable, and professional.

© 2025 MATLABit. All rights reserved.

Monday, July 21, 2025

Mathematical Operations Using MATLAB

MATLABit

MATLAB stands for MATrix LABoratory. It’s a powerful programming language and software tool created by MathWorks. Its extensive application across engineering, scientific research, academic instruction, and algorithmic design stems from its strengths in numerical computation, data analysis, graphical visualization, and simulation. With a foundation in matrix algebra, MATLAB efficiently manages large datasets and complex mathematical models. Thus, we are well-positioned to commence our exploration of its capabilities. So, let's get started using MATLAB as a calculator.

Table of Contents

Mathematical Operations

In this chapter, we focus exclusively on arithmetic operations with scalars, which are simply numbers.

Scalars can be used in calculations in two ways:

  • Directly, just like you would on a calculator
  • Through variables, where numbers are first assigned to variables and then used in expressions

Below is a list of common arithmetic operations along with their symbols and examples. These operations are similar to what you'd find on most calculators, except for left division, which is used primarily in array operations.

Operation Symbol Example Description
Addition + 8 + 2 Adds two numbers
Subtraction - 10 - 4 Subtracts second number from the first
Multiplication * 6 * 7 Multiplies two numbers
Right Division / 12 / 4 Divides 12 by 4 (normal division)
Left Division \ 12 \ 4 Equivalent to 4 / 12 (inverse of right division for scalars)
Exponentiation ^ 3 ^ 4 Raises 3 to the power of 4 (i.e., 3⁴ = 81)

Order of Precedence

MATLAB follows a specific order when executing arithmetic operations. This order of precedence is similar to what is used in most standard calculators. The table below outlines the order in which MATLAB evaluates expressions:

Precedence Level Mathematical Operation Description
First Parentheses Expressions within parentheses are evaluated first. For nested parentheses, the innermost set is evaluated first.
Second Exponentiation Operations using exponents (e.g., ^) are evaluated after parentheses.
Third Multiplication and Division Both have equal precedence and are evaluated from left to right.
Fourth Addition and Subtraction These operations have the lowest precedence and are also evaluated from left to right.

When an expression has more than one operation, the ones with higher precedence are done first. If two or more operations have the same level of precedence, MATLAB evaluates them from **left to right**.

Applications

One of the simplest and most common ways to use MATLAB is as a basic calculator. This is done through the Command Window, where you can type any valid mathematical expression. Once you press the Enter key, MATLAB immediately processes the expression and displays the result.

The output appears on the next line, typically starting with ans =, which stands for "answer." This is the default variable MATLAB uses to store the result if no specific variable name is provided.

For example, if you type 3 + 5 and press Enter, MATLAB will respond with:

ans = 8

Expression Explanation Result
10 + 6 / 2 6 / 2 is evaluated first, then added to 10 13
(10 + 6) / 2 10 + 6 is grouped and added first, then divided 8
3 + 6 / 2 + 4 6 / 2 is done first, then the additions left to right 10
4 ^ 3 / 2 4^3 = 64 is done first, then divided by 2 32
64 ^ (1/3) + 25 ^ 0.5 Cube root of 64 and square root of 25 are calculated, then added 4 + 5 = 9
64 ^ 1/3 + 25 ^ 0.5 64 ^ 1 then divided by 3 (wrong precedence) 21.3333
0.5 - (0.5)^3 / (1*2*3) + 0.5^5 / (1*2*3*4*5) Each term is evaluated using powers and factorials ≈ 0.4792

✨Conclusion

  • 😊 MATLAB as a calculator: The Command Window allows you to do direct calculations, just like with a standard calculator.
  • 😊 The order of operations in MATLAB is as follows: Brackets or grouping "()", Powers ".^" , Multiplication "✖️" & Division "➗", then Addition "➕" & Subtraction "➖".
  • 😊 Use of variables: Expressions can involve direct numbers or stored variables for better flexibility and reuse.
  • 😊 Left vs Right Division: Remember, `5 / 3` is normal division, while `5 \ 3` gives the inverse.
  • 🙁 Common Mistake: Forgetting parentheses can lead to wrong results due to precedence rules—always double-check!
  • 😊 Practice makes perfect: Try more expressions and use the Command Window to observe how MATLAB evaluates them step-by-step.

With these fundamentals in mind, you're now equipped to start exploring MATLAB more confidently and effectively. 🎯

© 2025 MATLABit. All rights reserved.

Sunday, July 20, 2025

Working in the Command Window

MATLABit

MATLAB stands for MATrix LABoratory. It’s a powerful programming language and software tool created by MathWorks. Its extensive application across engineering, scientific research, academic instruction, and algorithmic design stems from its strengths in numerical computation, data analysis, graphical visualization, and simulation. With a foundation in matrix algebra, MATLAB efficiently manages large datasets and complex mathematical models. Thus, we are well-positioned to commence our exploration of its capabilities. So, let's start working in the command window and learn how to use editor window with it.

Table of Contents

Introduction

When MATLAB is started for the first time for beginners it appears to be convenient to close all windows except for Command window. Users can reactivate the hidden windows by choosing them from the layout menu accessible within the Toolstrip menu bar. The windows can be displayed by clicking on the layout icon and selecting Default in the menu that opens. The various windows in are docked to the desktop. A window can be undocked (become a separate, independent window) by dragging it out. An independent window can be redocked by clicking on the pulldown menu at the top right-hand side of the window and then selecting Dock.

Guidelines for Working in Command Window

  • To enter a command in MATLAB, place the cursor beside the command prompt symbol >>.
  • Once you type a command and press Enter, only the most recent command is executed. Any previously executed commands remain unchanged, even if still visible.
  • You can enter multiple commands on the same line by separating them with commas. MATLAB will execute them in order from left to right when you press Enter.
  • It is not possible to go back and edit a previous line directly in the Command Window. To modify a command, you must retype it at the prompt.
  • To enter a command in MATLAB, place the cursor beside the command prompt symbol >>.
  • Once you type a command and press Enter, only the most recent command is executed. Any previously executed commands remain unchanged, even if still visible.
  • You can enter multiple commands on the same line by separating them with commas. MATLAB will execute them in order from left to right when you press Enter.
  • It is not possible to go back and edit a previous line directly in the Command Window. To modify a command, you must retype it at the prompt.
  • A previously typed command can be recalled to the command prompt by pressing the up-arrow key (↑). Once recalled, the command can be modified if needed and re-executed.
  • The down-arrow key (↓) is used to move forward through the list of previously typed commands.
  • If a command does not fit on a line, you can continue the command on the next line by typing three periods ... and pressing Enter. The remaining part of the command goes in the next line.
  • A command can be continued across multiple lines this way, up to a maximum of 4,096 characters.
  • The semicolon (;): When a command is entered in the Command Window and the Enter key is pressed, the command is executed and any output it generates is displayed.

    If a semicolon (;) is typed at the end of the command, the output is suppressed and will not be shown in the Command Window. This is useful when the result is already known or when the output is very large.
  • If multiple commands are typed on the same line, and a semicolon (;) is used instead of a comma, the outputs from those commands will also be hidden.
  • Typing the percent sign (%): When a line begins with the percent symbol (%), it is treated as a comment. Pressing Enter will not execute this line.

    Additionally, you can prompt from the same line by using % after a command. This would have no influence on how the command will operate.
  • The clc command:
    In MATLAB, typing clc followed by Enter will clear the Command Window. This is helpful when the display becomes too long or cluttered after entering many commands.
  • Clearing the command window with clc will not wipe any existing variables you are working with, nor revert any actions done before that Editor Window. All previously defined variables remain in the workspace and can still be used.
  • Even after clearing the Command Window with clc, you can still use the up-arrow key (↑) to recall and reuse previously entered commands.

Guidelines for Working in Editor Window

  • Editor Window is used to write, save a file and also to edit script and function files in MATLAB. It provides a dedicated environment for working with larger sets of code.
  • Files saved from the editor are generally saved in. m extension and are referred to as script or function files. Contrary to the Command Window, the Editor allows you write several lines of code and execute them altogether.
  • To run code from the Editor, click the Run button or press F5. The output is displayed in the Command Window.
  • The Editor supports features such as syntax highlighting, automatic indentation, code folding, and error checking, which make coding more efficient and readable.
  • Comments can be added in the Editor using the percent sign %, just like in the Command Window. These comments are helpful for documenting your code.
  • The Editor also supports breakpoints for debugging. You can click on the left margin next to a line number to set a breakpoint and inspect variable values during execution.
  • While editing, unsaved changes are indicated with an asterisk (*) in the tab or title bar. Be sure to save your work regularly using Ctrl + S or the save icon.

Command History Window

  • The Command History Window displays a list of all commands that have been entered in the Command Window, including commands from previous MATLAB sessions.
  • Any command shown in the Command History can be reused. Simply double-click a command to automatically re-enter and execute it in the Command Window.
  • Alternatively, you can drag and drop a command from the Command History into the Command Window, modify it if necessary, and then press Enter to run it.
  • To delete specific commands from the Command History, select the lines, right-click, and choose Delete Selection from the menu.
  • To delete all of the command history, right-click anywhere in the Command History Window and choose Clear Command History from the menu that pops up.

Conclusion

In today’s rapidly evolving technological landscape, tools like MATLAB play a pivotal role in driving innovation, research, and data-driven decision-making. Mastering the use of its essential components—such as the Command Window, Editor Window, and Command History—empowers users to efficiently write, execute, and manage code for complex analytical tasks.

From controlling output display with semicolons and ellipses to writing reusable scripts and recalling past commands, MATLAB offers a streamlined and intelligent environment tailored for problem-solving and simulation. These practices not only enhance coding fluency but also build the foundation for tackling real-world challenges across engineering, science, and industry.

As we move forward into an era dominated by automation, artificial intelligence, and advanced computation, developing proficiency in MATLAB is more than an academic achievement—it’s a vital skill that equips individuals to contribute meaningfully to a future shaped by technology.

© 2025 MATLABit. All rights reserved.

Saturday, July 19, 2025

Starting with MATLAB

MATLABit

MATLAB stands for MATrix LABoratory. It’s a powerful programming language and software tool created by MathWorks. Its extensive application across engineering, scientific research, academic instruction, and algorithmic design stems from its strengths in numerical computation, data analysis, graphical visualization, and simulation. With a foundation in matrix algebra, MATLAB efficiently manages large datasets and complex mathematical models. Thus, we are well-positioned to commence our exploration of its capabilities. So, let's get started with it.

Table of Contents

Introduction

MATLAB enjoys extensive adoption in universities and research laboratories for both introductory and advanced coursework spanning mathematics, the natural sciences, and particularly engineering disciplines. In the industrial sector, the environment supports research, development, and product design. The core MATLAB environment provides a comprehensive suite of built-in functions and toolboxes, allowing users to tackle a broad array of standard analytical and computational challenges.

MATLAB Windows

1. Command Window

This is where you directly enter commands, perform calculations, or run scripts. It acts as the main interactive area for executing MATLAB code line-by-line.

2. Command History

This window keeps a record of all previously entered commands. You can re-run or copy past commands from here without retyping them.

3. Workspace

Displays all the variables currently stored in memory. You can see variable names, sizes, and values and double-click to inspect or edit them.

4. Editor

Used to write, edit, and save scripts or function files (e.g., `.m` files). It provides features like syntax highlighting and debugging tools.

5. Current Folder

Shows files and folders in the current directory. You can use this window to manage files and open scripts or data for your project.

6. Figure Window

This window displays graphical output such as plots, charts, or images generated using MATLAB commands like plot() or imshow().

7. Command Toolbar

A set of buttons that provides quick access to common actions like saving, opening, debugging, and running scripts.

8. Help Browser

Provides documentation and help topics on MATLAB functions, toolboxes, and usage examples. Very useful for learning and troubleshooting.

Applications

  • Engineering and Scientific Research: Modeling systems, solving equations, and simulating physical processes.
  • Signal Processing: Filtering, audio analysis, and signal transformation.
  • Image Processing and Computer Vision: Object detection, medical imaging, and video tracking.
  • Machine Learning and AI: Classification, deep learning, and predictive modeling.
  • Control Systems: PID tuning, system simulation, and Simulink-based modeling.
  • Data Analysis and Visualization: Plotting, statistical analysis, and dashboards.
  • Embedded Systems and Robotics: Code generation, sensor integration, and real-time testing.
  • Finance and Economics: Time-series analysis, simulations, and financial modeling.
  • Education and Teaching: Teaching math and science with simulations and live scripts.

Conclusion

From academic learning to cutting-edge industrial research, MATLAB serves as a versatile tool that bridges theory and practical application. Its ability to handle everything from image processing and machine learning to signal analysis and control systems makes it indispensable in both classrooms and laboratories. Whether you're designing a robot, simulating a financial model, or visualizing medical data, MATLAB empowers users with precision, speed, and ease of use—making it a cornerstone software for modern computational work.

© 2025 MATLABit. All rights reserved.

Division Operation Applied to Arrays in MATLAB

  MATLABit MATLAB stands for MATrix LABoratory. It’s a powerful programming language and software tool created by MathWorks. Its extensiv...