Hold on матлаб что это
Перейти к содержимому

Hold on матлаб что это

  • автор:

Глава 2. Построение графиков в matlab

MATLAB включает в себя мощные средства для визуализации данных, например, для представления их в виде двумерных графиков, гистограмм, линий уровня, трехмерных поверхностей и т.д. В таблице 2.1 приведены некоторые функции для отображения данных

Построение графика в виде двумерной линии

Построение графика в виде двумерной линии в логарифмическом масштабе

Построение графика в виде двумерной линии в полярных координатах

Построение графика в виде вертикальной гистограммы

Построение графика в виде горизонтальной гистограммы

Построение линий уровня

Построение линий уровня с использованием заливки цветом

Построение графика в виде трехмерной поверхности

Построение графика в виде трехмерной поверхности с отображением линий уровня

Построение графика в виде трехмерной сетки

Построение графика в виде трехмерной линии

Отображение данных в виде точек на плоскости

Отображение данных в виде точек в трехмерном пространстве

Отображение векторного поля на плоскости

Отображение векторного поля в пространстве

2.1. Построение графика в виде двумерной линии

Сначала рассмотрим построение двумерного графика y = f (x) в виде линии на плоскости. Для отображения таких данных используется функция plot. Вызывать эту функцию можно несколькими способами с использованием разного количества входных параметров, далее будут рассмотрены только некоторые из этих способов.

Если в функцию plot передать два параметра, представляющие собой одномерные вектора x и y – plot (x, y) – то будет проведена линия через точки, абсциссы которых задаются в качестве первого параметра, а ординаты – в качестве второго.

Следующий пример заполняет массив (матрицу-строку) значениями от 0 до 720 с шагом 1.0, к каждому значению матрицы применяет функцию sind (синус от угла, заданного в градусах) и выводит результат в виде графика.

После выполнения функции plot откроется окно, показанное на рисунке 2.1.

Если функцию plot вызвать с одним параметром (plot(y)), то по оси Y будут отложены последовательно значения элементов матрицы y, а по оси X будут отложены номера элементов матрицы y. В результате выполнения следующего примера будет выведен график, показанный на рисунке 2.2:

Функция plot также может принимать дополнительный параметр, который описывает внешний вид линии, которой будет нарисован график. Внешний вид линии описывается в виде строки, которая может содержать три составные части:

вид маркеров, добавляемых на линию;

Тип линии задается комбинацией символов, приведенных в таблице 2.2

Спецификатор

Внешний вид

Сплошная линия (значение по умолчанию)

Тип маркера задается комбинацией символов, приведенных в таблице 2.3

Спецификатор

Внешний вид маркера

p или pentagram

Цвет линии может быть задан с помощью символов, приведенных в таблице 2.4

Hold on матлаб что это

Hold current graph in the figure

Description

The hold function determines whether new graphics objects are added to the graph or replace objects in the graph.

hold on retains the current plot and certain axes properties so that subsequent graphing commands add to the existing graph.

hold off resets axes properties to their defaults before drawing new plots. hold off is the default.

hold toggles the hold state between adding to the graph and replacing the graph.

Test the hold state using the ishold function.

Although the hold state is on , some axes properties change to accommodate additional graphics objects. For example, the axes’ limits increase when the data requires them to do so.

The hold function sets the NextPlot property of the current figure and the current axes. If several axes objects exist in a figure window, each axes has its own hold state. hold also creates an axes if one does not exist.

hold on sets the NextPlot property of the current figure and axes to add .

Matlab hold on

Matlab hold on

The following article provides an outline for Matlab hold on. Matlab’s ‘hold’ command determines whether the newly created graphic object will be added to the existing graph or will it replace the existing objects in our graph. The command ‘hold on’ is used to retain our current plot & its axes properties in order to add subsequent graphic commands to our existing graph.

Python TutorialMachine LearningAWSArtificial Intelligence

TableauR ProgrammingPowerBIDeep Learning

For example, we can add 2 trigonometric waves, sine and cos, to the same graph using the hold on command.

Hadoop, Data Science, Statistics & others

Syntax:

  • Command ‘hold on’ is used to retain the plot in current axes. By doing so, the new plot is added to the existing axes without making any changes to the existing plot.
  • Command ‘hold off’ is used to change the hold on state back to off.

Examples of Matlab hold on

Let us see how to add a new plot to the existing axes in Matlab using the ‘hold on’ command.

Example #1

In this example, we will use the ‘hold on’ command to add 2 plots to a single graph. We will plot 2 different logarithmic functions in one graph for our 1 st example.

The steps to be followed for this example are:

  • Initialize the 1 st function to be plotted.
  • Use the plot method to display the 1 st function.
  • Use the ‘hold on’ command to ensure that the plot of the next function is added to this existing graph.
  • Initialize the 2 nd function to be plotted.
  • Use the plot method to display the 2 nd function.
  • Use the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph.

Code:

x = linspace (0, 5);

[Initializing the 1 st logarithmic function]

[Using the plot method to display the figure]

x = linspace (0, 5);

[Initializing the 2 nd logarithmic function]

[Using the plot method to display the figure]

[Using the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph]

This is how our input and output will look like in the Matlab command window.

Input:

Matlab hold on 1

Output:

Matlab hold on 2

As we can see in the output, we have obtained 2 logarithmic functions in the same graph as expected by us.

Example #2

In this example, we will use the ‘hold on’ command to add 2 different exponential functions in one graph.

The steps to be followed for this example are:

  • Initialize the 1 st function to be plotted.
  • Use the plot method to display the 1 st function.
  • Use the ‘hold on’ command to ensure that the plot of the next function is added to this existing graph.
  • Initialize the 2 nd function to be plotted.
  • Use the plot method to display the 2 nd function.
  • Use the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph.

Code:

[Initializing 1st exponential function]

[Using the plot method to display the figure]

[Initializing 2 nd exponential function]

[Using the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph]

This is how our input and output will look like in the Matlab command window.

Input:

Matlab hold on 3

Output:

to add 2 different exponential functions

As we can see in the output, we have obtained 2 exponential functions in the same graph as expected by us.

In the above 2 examples, we saw how to add 2 functions to a single graph. We can also use the same ‘hold on’ command to add more than 2 functions also. Next, we will see how to add 3 functions to the same graph.

Example #3

In this example, we will use the ‘hold on’ command to add 3 plots to a single graph. We will plot 3 different exponential functions in one graph for this example.

The steps to be followed for this example are:

  • Initialize the 1 st function to be plotted.
  • Use the plot method to display the 1 st function.
  • Use the ‘hold on’ command to ensure that the next plot is added to this existing graph.
  • Initialize the 2 nd function to be plotted.
  • Use the plot method to display the 2 nd function.
  • Use the ‘hold on’ command to ensure that the next plot is added to this existing graph.
  • Initialize the 3 rd function to be plotted.
  • Use the plot method to display the 3 rd function.
  • Use the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph.

Code:

[Initializing 1st exponential function]

[Using the plot method to display the figure]

[Initializing 2 nd exponential function]

[Using the plot method to display the figure]

[Initializing 3 rd exponential function]

[Using the plot method to display the figure]

[Using the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph]

This is how our input and output will look like in the Matlab command window:

Input:

Matlab hold on 5

Output:

plot 3 different exponential functions

As we can see in the output, we have obtained 3 exponential functions in the same graph as expected by us.

Conclusion

Matlab’s ‘hold on’ command is used to add more than 1 graphic object to the same figure. This command is used to retain our current plot & its axes properties in order to add subsequent graphic commands to our existing graph.

Recommended Articles

This is a guide to Matlab hold on. Here we discuss the introduction to Matlab hold on along with examples for better understanding. You may also have a look at the following articles to learn more –

MATLAB Plots

Plots are useful in providing information in picture view and MATLAB provides the facility for creating a plot using plot command.

plot Command

The plot command in MATLAB help to create two-dimensional plots. The general form of the command is:

Line specifiers Style
(color)
Line specifiers Style
(marker)
Line specifiers Style
(line)
b Blue s Rectangle marker Dashed line
c Cyan o Circle : Dotted line
k Black x x-mark -. Dashpot
g Green + Plus (no line) None
y Yellow * Star Solid line
w White d Diamond
m Magenta . Point marker
r Red
  • x and y both are vectors.
  • The table below shows the following line specifiers which are Optional.

Examples

Program (1): To plot the curve for x and y values are given below, in MATLAB.

MATLAB VIEW – Program (1):

Create a script file in MATLAB and type the following code –

MATLAB VIEW – Output (1):

Program (2): To plot curve with a line specifiers as a dashed red line for x and y values are given below, in MATLAB.

MATLAB VIEW – Program (2):

Create a script file in MATLAB and type the following code –

MATLAB VIEW – Output (2):

In the above plot x vs. y, with a dashed red line.

Multiple graphs using plot command

The example below will show you how to show multiple graphs in the same plot using plot command in MATLAB.

Examples

Program (1): To show curve in same plot for functions f(x) and g(x) is given below in MATLAB.

f(x) = x; g(x) = 2x; 0 ≤ x ≤ 10

MATLAB VIEW – Program (1):

Create a script file in MATLAB and type the following code –

MATLAB VIEW – Output (1):

In the above figure f vs. x and g vs. x, all in the same plot.

hold on and hold off command

The example below will show you how to show multiple graphs in the same plot by using hold on and hold off command in MATLAB.

Example

Program (1): To show the curve for functions f(x) and g(x) in the same plot is given below, in MATLAB.

MATLAB VIEW – Program (1):

Create a script file in MATLAB and type the following code –

MATLAB VIEW – Output (1):

MATLAB – Plot formatting Using Commands:

The formatting commands are entered after the plot command. In MATLAB the various formatting commands are:

(1). The xlabel and ylabel commands:

The xlabel command put a label on the x-axis and ylabel command put a label on y-axis of the plot.

The general form of the command is:

(2). The title command:

This command is used to put the title on the plot. The general form of the command is:

(3). The axis command:

This command adds an axis to the plot. The general form of the command is:

(4). The grid command:

This command adds the grid to the plot. The general form of the command is:

Example

Program (1): To plot sine wave having following properties given below, in MATLAB.

f(x) = sin(x); 0 ≤ x ≤ 2π; Properties: Sine wave: axis and grid present, x-axis label “time”, y-axis label “amplitude”, title label” sine wave”.

MATLAB VIEW – Program (1):

Create a script file and type the following code –

MATLAB VIEW – Output (1):

Related Topics

title() command puts the title on the plot, after reading this MATLAB title topic, you will…

This command adds or removes grid lines to the plot, after reading this MATLAB grid topic,…

The ylabel command put the label on the y-axis of the plot, after reading this…

The xlabel command put the label on the x-axis of the plot, after reading this…

After reading the MATLAB 3-D plots topic, you will understand how to create 3-d plots…

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering. View all posts by Electrical Workbook

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *