Gca matlab что это

от admin

Некоторые полезные средства настройки графиков (plot) в MATLAB

Недавно, в очередной раз проверяя домашние работы своих студентов, я загорелся желанием автоматизировать этот процесс. Задание состояло в составлении рабочей таблицы девиации магнитного компаса и построения кривой девиации.

Входными данными служили показания магнитного компаса (МК), синхронно наблюдаемые показания гирокомпаса (ГК), поправка ГК и значение магнитного склонения для района, в котором проходили измерения.

Все данные были занесены в таблицу и разделены из 10 столбцов с входными данными и 25 строк – значений входных данных для каждого из вариантов. Для удобства считывания данных в MATLAB они были записаны в виде текстового файла и импортировались в рабочее пространство с помощью функции importdata.

По методике расчетов необходимо было обработать данные с помощью нескольких эмпирических формул для заполнения рабочей таблицы девиации МК. Однако, основным и наиболее наглядным результатом работы является построение кривой девиации МК.

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

И получен следующий график:

Разберем код построчно, рассмотрим какие параметры можно указывать для настройки отображения графиков.

Здесь задаются входные данные для построения графика. Количество значений по оси абсцисс и по оси ординат должно совпадать. По эти данные являются векторами с 36 значениями.

Собственно, функция построения графика, в которую передаются данные и параметры. Помимо очевидных входных данных параметром функции является тип отображаемой линии, закодированный трехсимвольным сочетанием. В данном случае “b” – blue, цвет линии; “o” – вид маркера, которым обозначаются точки графика и “-” – тип линии, в данном случае – сплошная.

Ниже привожу список параметров для настройки отображаемой линии.

Маркер Цвет линии
c голубой
m фиолетовый
y желтый
r красный
g зеленый
b синий
w белый
k черный

Маркер Тип линии
— непрерывная
— — штриховая
: пунктирная
-. штрих-пунктирная

Маркер Тип маркера
. точка
+ знак «плюс»
* знак «звездочка»
о круг
х знак «крест»

Команда, которой включается сетка на графике.

Подписи для графика и соответствующих осей. Здесь “\circ” кодировка символа градуса.

Команда управления осями. В данном случае выставлен параметр “auto” – автоматическая расстановка осей. Здесь-то меня и не устроила работа MATLAB, т.к. автоматически оси не пристыковывались к крайним значениям графика, а «добавляли» лишнее пространство по оси “X”.

С помощью команды “help axis” я нашел еще несколько вариантов параметра для осей, в частности попробовал параметр “tight”, который должен был пристыковывать границы графика к крайним значениям кривой. Однако результат и этого параметра меня не удовлетворил т.к. результат выглядел следующим образом:

График выглядит «зажатым», к тому же «теряются» части кривой находящиеся между максимальными значениями.

Для получения наглядного результата пришлось настроить ось “X” отдельно с помощью следующих команд:

Последняя функция задает граничные значения отдельно для оси “X”, что позволило мне ограничить график максимальными значениями по данной оси.

И последняя команда:

Позволила настроить подписи и шаг для оси “X”. Функция “set” является достаточно общей, ее работа зависит от передаваемых параметров. В данном случае “gca” – означает, что параметры будут устанавливаться для сетки графика, “ XTick ” – означает, что будет управляться подпись оси “X”, а параметр “0:45:360” – задает минимальное значение, шаг и максимальное значение.

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

Надеюсь, что эта статья будет полезной не только для начинающих MATLAB, но и для опытных пользователей.

В окончании хотел бы отметить полезность команды “help” – она не только позволяет получить необходимую информацию по функции или команде из командной строки, но и сделать это значительно быстрее, чем через поиск в справке MATLAB.

Gca matlab что это

Get current axes handle

Description

h = gca returns the handle to the current axes for the current figure. If no axes exists, MATLAB creates one and returns its handle. You can use the statement

if you do not want MATLAB to create an axes if one does not already exist.

The current axes is the target for graphics output when you create axes children. Graphics commands such as plot , text , and surf draw their results in the current axes. Changing the current figure also changes the current axes.

Русские Блоги

ax = gca returns the current axes or chart for the current figure, which is typically the last one created or clicked with the mouse.

ax = gca Возвращает текущую ось или диаграмму текущего графика, обычно последнюю ось, созданную или нажатую мышью.

Graphics functions, such as title , target the current axes or chart. Use ax to access and modify properties of the axes or chart. If axes or charts do not exist, then gca creates Cartesian axes.

Графические функции (например, заголовки) предназначены для текущей оси или диаграммы. Используйте топор для доступа и изменения свойств оси или диаграммы. Если ось или диаграмма не существует, gca создает декартову ось.

Specify Properties for Current Axes

Plot a sine wave.

x = linspace(0,10);
y = sin(4*x);
plot(x,y)

Set the font size, tick direction, tick length, and y-axis limits for the current axes. Use gca to refer to the current axes.
Note: Starting in R2014b, you can use dot notation to set properties. If you are using an earlier release, use the docid:matlab_ref.f67-432995 function instead, such as set(ax,’FontSize’,12).

ax = gca; % current axes
ax.FontSize = 12;
ax.TickDir = ‘out’;
ax.TickLength = [0.02 0.02];
ax.YLim = [-2 2];

User interaction can change the current axes or chart. It is better to assign the axes or chart to a variable when you create it instead of relying on gca .

Взаимодействие с пользователем может изменить текущую ось или график. Лучше назначать оси или диаграммы переменным при их создании, чем полагаться на gca.

Changing the current figure also changes the current axes or chart.

Изменение текущего графика также изменяет текущую ось или график.

Set axes properties after plotting since some plotting functions reset axes properties.

Установите свойства оси после рисования, потому что некоторые функции рисования сбрасывают свойства оси.

To access the current axes or chart without forcing the creation of Cartesian axes, query the figure CurrentAxes property. MATLAB® returns an empty array if there is no current axes.

Читать:
Как сделать черный фон в ворде

Чтобы получить доступ к текущей оси или диаграмме без принудительного создания декартовой оси, запросите свойство CurrentAxes графического объекта. Если текущей оси нет, MATLAB® возвращает пустой массив.

В приведенном выше примере, если вы добавите оператор:

fig = gcf; ax = fig.CurrentAxes;

XLim: [0 2]
YLim: [-100 20]
XScale: ‘linear’
YScale: ‘linear’
GridLineStyle: ‘-‘
Position: [0.1300 0.1100 0.7750 0.8150]
Units: ‘normalized’

Matlab gca

By Priya PedamkarPriya Pedamkar

Matlab gca

Introduction to Matlab gca

MATLAB’s ‘gca’ method can be used to get the handle for our current axis. Also, if we don’t have any handle, then the ‘gca’ method will generate one. To refresh our understanding of handle, please keep in mind that handle is basically a number that will refer to an Object. This Object can be a figure, axes, or lines. If we need to perform any changes to the Object, we will require a reference to the object which can be done using the handle.

Python TutorialMachine LearningAWSArtificial Intelligence

TableauR ProgrammingPowerBIDeep Learning

Syntax:

Hadoop, Data Science, Statistics & others

ca = gca will return the handle to current axes in the figure.

Let us now understand how to get the current axes in MATLAB using ‘gca’ method.

Examples

Let us discuss examples of Matlab gca.

Example #1

In this example, we will use gca method to get the current axes of our figure. We will plot an exponential function for our first example. The steps to be followed for this example are:

  1. Initialize the function whose current axes is required
  2. Use the plot method to display the figure
  3. Initialize the gca method
  4. Set the font size for the current axes
  5. Set the current axes’ limit for the current axes

Code:

x = linspace (0, 20);
y = exp (2 * x);

[Initializing the x & y axis. Here we are using an exponential function]

[Using the plot method to display the figure]

[Using the ‘gca’ method for referring to current axes]

[Setting the font size for the current axes]

[Setting the current axes’ limit]

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

Input:

matlab gca 1

Output 1:

Plot of the exponential function

matlab gca 2

Output 2:

Getting the current axes of the above figure

matlab gca 3

As we can see in the OUTPUT, we have obtained the current axes of the exponential function defined by us.

Example #2

In this example, we will use gca method to get the current axes of our figure. We will plot a sine wave for this example. The steps to be followed for this example are:

  1. Initialize the function whose current axes is required
  2. Use the plot method to display the figure
  3. Initialize the gca method
  4. Set the font size for the current axes
  5. Set the current axes’ limit for the current axes

Code:

x = linspace (0, 30);
y = sin (10 * x);

[Initializing the x & y axis. Here we are defining a sine wave]

[Using the plot method to display the figure]

[Using the ‘gca’ method for referring to current axes]

[Setting the font size for the current axes]

[Setting the current axes’ limit for the current axes]

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

Input:

matlab gca 4

Output 1:

Plot of the sine wave

matlab gca 5

Output 2:

Getting the current axes of above figure

matlab gca 6

As we can see in the OUTPUT, we have obtained the current axes of the sine wave defined by us.

Example #3

In this example, we will use gca method to get the current axes of our figure. We will plot a cos wave for this example. The steps to be followed for this example are:

  1. Initialize the function whose current axes is required
  2. Use the plot method to display the figure
  3. Initialize the gca method
  4. Set the font size for the current axes
  5. Set the current axes’ limit for the current axes

Code:

x = linspace (0, 20);
y = cos (10 * x);

[Initializing the x & y axis. Here we are defining a cos wave]

[Using the plot method to display the figure]

[Using the ‘gca’ method for referring to current axes]

[Setting the font size for the current axes]

[Setting the current axes’ limit for the current axes]

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

Input:

matlab gca 7

Output 1:

Plot of the cos wave

example 3

Output 2:

Getting the current axes of above figure

example 3-1

As we can see in the OUTPUT, we have obtained the current axes of the cos wave defined by us.

Example #4

In this example, we will use gca method to get the current axes of our figure. We will plot a logarithmic function for this example. The steps to be followed for this example are:

  1. Initialize the function whose current axes is required
  2. Use the plot method to display the figure
  3. Initialize the gca method
  4. Set the font size for the current axes
  5. Set the current axes’ limit for the current axes

Code:

x = linspace (0, 20);
y = log (10 * x);

[Initializing the x & y axis. Here we are defining a logarithmic function]

[Using the plot method to display the figure]

[Using the ‘gca’ method for referring to current axes]

[Setting the font size for the current axes]

[Setting the current axes’ limit for the current axes]

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

Input:

example 4

Output 1:

Plot of the logarithm function

example 4-1

Output 2:

Getting the current axes of above figure

example 4-2

As we can see in the OUTPUT, we have obtained the current axes of the logarithm function defined by us.

Conclusion

In MATLAB, gca method is used to get the handle for our current axis. If there is no handle, then the ‘gca’ method will generate one.

Recommended Articles

This is a guide to Matlab gca. Here we discuss the introduction, syntax, and steps with output with examples for better understanding. You may also have a look at the following articles to learn more –

Похожие статьи