Как построить прямую в матлабе
Документация
Создайте примитивную линию
Синтаксис
Описание
line чертит линию от точки (0,0) к (1,1) с настройками свойства по умолчанию.
Примеры
Сюжетная линия Используя векторные данные
Построение нескольких графиков Используя матричные данные
Постройте два графика путем определения x и y как матрицы. Используйте line построить столбцы y по сравнению со столбцами x как разделяют линии.
Сюжетная линия с 3-D координатами
Сюжетная линия Используя низкоуровневый синтаксис
Создайте x и y как векторы. Затем вызовите низкоуровневую версию line функция путем определения данных как аргументов пары «имя-значение». Когда вы вызываете функцию этот путь, получившаяся линия является черной.
Specify Line Properties
Проведите красную, пунктирную линию между точками (1,2) и (9,12). Установите Color и LineStyle свойства как пары «имя-значение».
Change Line Properties после создания
Во-первых, чертите линию от точки (3,15) до (2,12) и возвратите Line объект. Затем измените линию в зеленую, пунктирную линию. Используйте запись через точку, чтобы установить свойства.
Входные параметры
x — Первая координата
вектор | матрица
Первая координата в виде вектора или матрицы. Матричные входные параметры поддерживаются для Осей декартовой системы координат только.
Если x и y оба векторы с той же длиной, затем line строит одну строку.
Если один из x или y вектор, и другой матрица, затем line строит несколько графиков. Длина вектора должна равняться одной из матричных размерностей:
Если длина вектора равняется количеству строк матрицы, то line строит график каждого столбца матрицы вдоль вектора.
Если длина вектора равняется количеству столбцов матрицы, то line строит график каждой строки матрицы вдоль вектора.
Если матрица является квадратной, то line строит график каждого столбца вдоль вектора.
Для полярных осей первая координата является углом в полярных координатах θ в радианах. Для географических осей первая координата является широтой в градусах. К сюжетным линиям в этих типах осей, x и y должен быть одного размера.
Пример: x = linspace(0,10,25)
Типы данных: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration
y — Вторая координата
вектор | матрица
Вторая координата в виде вектора или матрицы. Матричные входные параметры поддерживаются для Осей декартовой системы координат только.
Если x и y оба векторы с той же длиной, затем line строит одну строку.
Если один из x или y вектор, и другой матрица, затем line строит несколько графиков. Длина вектора должна равняться одной из матричных размерностей:
Если длина вектора равняется количеству строк матрицы, то line строит график каждого столбца матрицы вдоль вектора.
Если длина вектора равняется количеству столбцов матрицы, то line строит график каждой строки матрицы вдоль вектора.
Если матрица является квадратной, то line строит график каждого столбца вдоль вектора.
Для полярных осей вторая координата является радиусом в модулях данных. Для географических осей вторая координата является долготой в градусах. К сюжетным линиям в этих типах осей, x и y должен быть одного размера.
Пример: y = sin(x)
Типы данных: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration
z — Третья координата
вектор | матрица
Третья координата в виде вектора или матрицы. Матричные входные параметры поддерживаются для Осей декартовой системы координат только.
Пример: z = sin(x) + cos(y)
Типы данных: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration
ax — Целевые оси
Axes возразите | PolarAxes возразите | GeographicAxes объект
Целевые оси в виде Axes объект, PolarAxes объект или GeographicAxes объект. Если вы не задаете оси, то line графики функций в текущей системе координат.
Аргументы name-value
Пример: line(x,y,’Color’,’red’,’LineWidth’,3) создает красную линию, которая является 3 широкими точками.
Цвет линии в виде триплета RGB, шестнадцатеричного цветового кода, названия цвета или краткого названия.
Для пользовательского цвета задайте триплет RGB или шестнадцатеричный цветовой код.
Кроме того, вы можете задать имена некоторых простых цветов. Эта таблица приводит опции именованного цвета, эквивалентные триплеты RGB и шестнадцатеричные цветовые коды.
Иллюстрированный самоучитель по MatLab
Построение графиков отрезками прямых
Одно из достоинств системы MATLAB – обилие средств графики, начиная от команд построения простых графиков функций одной переменной в декартовой системе координат и кончая комбинированными и презентационными графиками с элементами анимации, а также средствами проектирования графического пользовательского интерфейса (GUI). Особое внимание в системе уделено трехмерной графике с функциональной окраской отображаемых фигур и имитацией различных световых эффектов.
Описанию графических функций и команд посвящена обширная электронная книга в формате PDF. Объем материала по графике настолько велик, что помимо вводного описания графики в уроке 3 в этой книге даются еще два урока по средствам обычной и специальной графики. Они намеренно предшествуют систематизированному описанию большинства функций системы MATLAB, поскольку графическая визуализация вычислений довольно широко используется в последующих материалах книги. При этом графические средства системы доступны как в командном режиме вычислений, так и в программах. Этот урок рекомендуется изучать выборочно или выделить на него не менее 4 часов.
Функции одной переменной у(х) находят широкое применение в практике математических и других расчетов, а также в технике компьютерного математического моделирования. Для отображения таких функций используются графики в декартовой (прямоугольной) системе координат. При этом обычно строятся две оси – горизонтальная X и вертикальная Y, и задаются координаты х и у, определяющие узловые точки функции у(х). Эти точки соединяются друг с другом отрезками прямых, т. е. при построении графика осуществляется линейная интерполяция для промежуточных точек. Поскольку MATLAB – матричная система, совокупность точек у(х) задается векторами X и Y одинакового размера.
Команда plot служит для построения графиков функций в декартовой системе координат. Эта команда имеет ряд параметров, рассматриваемых ниже.
Приведенный ниже пример иллюстрирует построение графиков двух функций – sin(x) и cos(x), значения функции которых содержатся в матрице Y, а значения аргумента х хранятся в векторе X:
На рис. 6.1 показан график функций из этого примера. В данном случае отчетливо видно, что график состоит из отрезков, и если вам нужно, чтобы отображаемая функция имела вид гладкой кривой, необходимо увеличить количество узловых точек. Расположение их может быть произвольным.
Рис. 6.1. Графики двух функций в декартовой системе координат
Вот пример использования команды plot(Y):
Как построить прямую в матлабе
Syntax
Description
To plot a set of coordinates connected by line segments, specify X and Y as vectors of the same length.
To plot multiple sets of coordinates on the same set of axes, specify at least one of X or Y as a matrix.
plot( X 1, Y 1. X n, Y n) plots multiple pairs of x— and y-coordinates on the same set of axes. Use this syntax as an alternative to specifying coordinates as matrices.
plot( X 1, Y 1, LineSpec 1. X n, Y n, LineSpec n) assigns specific line styles, markers, and colors to each x— y pair. You can specify LineSpec for some x— y pairs and omit it for others. For example, plot(X1,Y1,’o’,X2,Y2) specifies markers for the first x— y pair but not for the second pair.
plot( Y ) plots Y against an implicit set of x-coordinates.
Examples
Create Line Plot
Plot Multiple Lines
Create Line Plot From Matrix
Define Y as the 4-by-4 matrix returned by the magic function.
Specify Line Style
Plot three sine curves with a small phase shift between each line. Use the default line style for the first line. Specify a dashed line style for the second line and a dotted line style for the third line.
MATLAB® cycles the line color through the default color order.
Specify Line Style, Color, and Marker
Plot three sine curves with a small phase shift between each line. Use a green line with no markers for the first sine curve. Use a blue dashed line with circle markers for the second sine curve. Use only cyan star markers for the third sine curve.
Display Markers at Specific Data Points
Create a line plot and display markers at every fifth data point by specifying a marker symbol and setting the MarkerIndices property as a name-value pair.
Specify Line Width, Marker Size, and Marker Color
Create a line plot and use the LineSpec option to specify a dashed green line with square markers. Use Name,Value pairs to specify the line width, marker size, and marker colors. Set the marker edge color to blue and set the marker face color using an RGB color value.
Add Title and Axis Labels
Plot Durations and Specify Tick Format
Define t as seven linearly spaced duration values between 0 and 3 minutes. Plot random data and specify the format of the duration tick marks using the ‘DurationTickFormat’ name-value pair argument.
Specify Axes for Line Plot
Modify Lines After Creation
Change the line width of the first line to 2. Add star markers to the second line. Use dot notation to set properties.
Plot Circle
Plot a circle centered at the point (4,3) with a radius equal to 2. Use axis equal to use equal data units along each coordinate direction.
Input Arguments
X — x-coordinates
scalar | vector | matrix
x-coordinates, specified as a scalar, vector, or matrix. The size and shape of X depends on the shape of your data and the type of plot you want to create. This table describes the most common situations.
Specify X and Y as scalars and include a marker. For example:
Specify X and Y as any combination of row or column vectors of the same length. For example:
Specify consecutive pairs of X and Y vectors. For example:
If all the sets share the same x— or y-coordinates, specify the shared coordinates as a vector and the other coordinates as a matrix. The length of the vector must match one of the dimensions of the matrix. For example:
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration
Y — y-coordinates
scalar | vector | matrix
y-coordinates, specified as a scalar, vector, or matrix. The size and shape of Y depends on the shape of your data and the type of plot you want to create. This table describes the most common situations.
Specify X and Y as scalars and include a marker. For example:
Specify X and Y as any combination of row or column vectors of the same length. For example:
Alternatively, specify just the y-coordinates. For example:
Specify consecutive pairs of X and Y vectors. For example:
If all the sets share the same x— or y-coordinates, specify the shared coordinates as a vector and the other coordinates as a matrix. The length of the vector must match one of the dimensions of the matrix. For example:
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration
LineSpec — Line style, marker, and color
character vector | string
Line style, marker, and color, specified as a character vector or string containing symbols. The symbols can appear in any order. You do not need to specify all three characteristics (line style, marker, and color). For example, if you omit the line style and specify the marker, then the plot shows only the marker and no line.
Example: ‘—or’ is a red dashed line with circle markers
ax — Target axes
Axes object | PolarAxes object | GeographicAxes object
Target axes, specified as an Axes object, a PolarAxes object, or a GeographicAxes object. If you do not specify the axes, MATLAB plots into the current axes or it creates an Axes object if one does not exist.
To create a polar plot or geographic plot, specify ax as a PolarAxes or GeographicAxes object. Alternatively, call the polarplot or geoplot function.
Name-Value Arguments
Example: ‘Marker’,’o’,’MarkerFaceColor’,’red’
Line color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short name.
For a custom color, specify an RGB triplet or a hexadecimal color code.
Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.
Color Name | Short Name | RGB Triplet | Hexadecimal Color Code | Appearance | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|
‘red’ | ‘r’ | [1 0 0] | ‘#FF0000’ |
RGB Triplet | Hexadecimal Color Code | Appearance |
---|---|---|
[0 0.4470 0.7410] | ‘#0072BD’ | |
‘none’ | No line | No line |
LineWidth — Line width
0.5 (default) | positive value
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is less than the width of a pixel on your system, the line displays as one pixel wide.
Marker symbol, specified as one of the values listed in this table. By default, the object does not display markers. Specifying a marker symbol adds markers at each data point or vertex.
MarkerIndices — Indices of data points at which to display markers
1:length(YData) (default) | vector of positive integers | scalar positive integer
Indices of data points at which to display markers, specified as a vector of positive integers. If you do not specify the indices, then MATLAB displays a marker at every data point.
Note
To see the markers, you must also specify a marker symbol.
Example: plot(x,y,’-o’,’MarkerIndices’,[1 5 10]) displays a circle marker at the first, fifth, and tenth data points.
Example: plot(x,y,’-x’,’MarkerIndices’,1:3:length(y)) displays a cross marker every three data points.
Example: plot(x,y,’Marker’,’square’,’MarkerIndices’,5) displays one square marker at the fifth data point.
For a custom color, specify an RGB triplet or a hexadecimal color code.
Alternatively, you can specify some common colors by name. This table lists the named color options, the equivalent RGB triplets, and hexadecimal color codes.
Color Name | Short Name | RGB Triplet | Hexadecimal Color Code | Appearance | ||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
‘red’ | ‘r’ | [1 0 0] | ‘#FF0000’ |
RGB Triplet | Hexadecimal Color Code | Appearance | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
[0 0.4470 0.7410] | ‘#0072BD’ |
Color Name | Short Name | RGB Triplet | Hexadecimal Color Code | Appearance | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
‘red’ | ‘r’ | [1 0 0] | ‘#FF0000’ |
RGB Triplet | Hexadecimal Color Code | Appearance | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
[0 0.4470 0.7410] | ‘#0072BD’ |
Value of DurationTickFormat | Description |
---|---|
‘y’ | Number of exact fixed-length years. A fixed-length year is equal to 365.2425 days. |
‘d’ | Number of exact fixed-length days. A fixed-length day is equal to 24 hours. |
‘h’ | Number of hours |
‘m’ | Number of minutes |
‘s’ | Number of seconds |
Example: ‘DurationTickFormat’,’d’ displays duration values in terms of fixed-length days.
To display a duration in the form of a digital timer, specify one of these values.
In addition, you can display up to nine fractional second digits by appending up to nine S characters.
Example: ‘DurationTickFormat’,’hh:mm:ss.SSS’ displays the milliseconds of a duration value to three digits.
DurationTickFormat is not a chart line property. You must set the tick format using the name-value pair argument when creating a plot. Alternatively, set the format using the xtickformat and ytickformat functions.
The TickLabelFormat property of the duration ruler stores the format.
Use NaN and Inf values to create breaks in the lines. For example, this code plots the first two elements, skips the third element, and draws another line using the last two elements:
plot uses colors and line styles based on the ColorOrder and LineStyleOrder properties of the axes. plot cycles through the colors with the first line style. Then, it cycles through the colors again with each additional line style.
Starting in R2019b, you can change the colors and the line styles after plotting by setting the ColorOrder or LineStyleOrder properties on the axes. You can also call the colororder function to change the color order for all the axes in the figure.
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
Usage notes and limitations:
Supported syntaxes for tall arrays X and Y are:
- баста театр без крыши
- аренда квартир с регистрацией