Select variable to plot матлаб как исправить ошибку

Hello I have a vector and a matrix obtained from another function, but the structure is like the vector and matrix inside 'callplot'. The code, is just like this. I really dont know how t...

Jose

Hello

I have a vector and a matrix obtained from another function, but the structure is like the vector

and matrix inside ‘callplot’.

The code, is just like this. I really dont know how to write in the right way this

inside the if function.

function f=callplot

t1=[0;1;2;3;4;5];

y1=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16; 17 18 19 20; 21 22 23 24];

in1=0; in2=0; in3=0; in4=0;

a=0; b=0; c=0;

while in1~=‘Y’||‘N’;

in1=input(‘¿You want to plot the variable X? (Y/N)’,‘s’);

if in1==‘Y’ pl(1:2)=‘t1,y1(:,1)’; elseif in1==‘N’ a=1; end

end

while in2~=‘Y’||‘N’;

in2=input(‘¿You want to plot the variable R? (Y/N)’,‘s’);

if in2==‘Y’ pl(3-2*a:4-2*a)=‘t1,y1(:,2)’; elseif in2==‘N’ b=1; end

end

while in3~=‘Y’||‘N’;

in3=input(‘¿You want to plot the variable N? (Y/N)’,‘s’);

if in3==‘Y’ pl(5-2*(a+b):6-2*(a+b))=‘t1,y1(:,2)’; elseif in3==‘N’ c=1; end

end

while in4~=‘Y’||‘N’;

in4=input(‘¿You want to plot the variable Z? (Y/N)’,‘s’);

if in4==‘Y’ pl(7-2*(a+b+c):8-2*(a+b+c))=‘t1,y1(:,2)’; end

end

plot(pl)

end

The error displayed when I Input Y is:

??? Subscripted assignment dimension mismatch.

Error in ==> callplot at 9 if in1==’Y’ pl(1:2)=’t1,y1(:,1)’; elseif in1==‘N’ a=1; end

Additionally, it looks like the elseif isn’t working either. When I Input N, it just display the

prompt again (It should only happen when input is different from Y or N). I suspect my error is on the ~=’Y’||’N’

I hope to be clear enough, sorry if my english is not good.

Accepted Answer

Aaditya Kalsi

The short answer is writing code like this is bad practice when it comes to changing it later and may bring many other problems. The other short answer is EVAL. You can use something like:

The better way to do this:

answersGiven = {in1; in2; in3; in4; in5};

boolCols = strcmpi(‘y’, answersGiven);

colNums = find(boolCols == true);

This should do it. I didn’t have MATLAB open so the code may gve errors! Sorry about that. But the idea should be pretty clear.


More Answers (1)

Walter Roberson

is interpreted as

which is

while (in1~=‘Y’) || (‘N’ ~= 0)

Now as ‘N’ is not 0, the statement is always true.

You want an «and» instead of an «or»

while in1~=‘Y’ && in1 ~=‘N’;

What do you want

to mean?

Sparta

2 / 2 / 0

Регистрация: 24.06.2010

Сообщений: 39

1

09.11.2010, 23:54. Показов 8767. Ответов 5

Метки нет (Все метки)


помогите пожалуйста. Может меня просто заклинило но я реально не понимаю почему MATLAB выдаёт такую ошибку
??? Error using ==> plot
Conversion to double from sym is not possible.

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
clc; clear;
z=1000; k=0; g=0; e=0;
s=int('1/(x+1)','x',0,5);
for i=1:z
    x= unifrnd(0,5);
    y= unifrnd(0,1);
    
    if (y<(1/(x+1)))
        k=k+1;
    end;
    
    if (mod(i,25)==0)
        e=e+1;
        d(e)=((s-(k/i)*5)/s)*100;
        j(e)=i;
    end;
    if (mod(i,250)==0)
        g=g+1;
        s1(g)=(k/i)*5;
        f(g)=i;
    end;
end;
plot(j,d);
xlabel('f-колличество испытаний');
ylabel('d-относительная погрешность');
ezplot('log(6)',f(1),z);
ylim([1.6,2]);
plot(f,s1);

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Sergik1

128 / 127 / 10

Регистрация: 09.11.2010

Сообщений: 200

10.11.2010, 16:42

2

Какая версия Matlab у Вас. На 2010b скрипт посчитался. См. скрин.
Как-то всё напутанно с выводом графики….
Попробуйте такой вариант:

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
clc; clear;
z=1000; k=0; g=0; e=0;
s=int('1/(x+1)','x',0,5);
for i=1:z
    x= unifrnd(0,5);
    y= unifrnd(0,1);
    
    if (y<(1/(x+1)))
        k=k+1;
    end;
    
    if (mod(i,25)==0)
        e=e+1;
        d(e)=((s-(k/i)*5)/s)*100;
        j(e)=i;
    end;
    if (mod(i,250)==0)
        g=g+1;
        s1(g)=(k/i)*5;
        f(g)=i;
    end;
end;
figure
plot(j,d);
xlabel('f-колличество испытаний');
ylabel('d-относительная погрешность');
title('Рис. 1')
figure
plot(f,s1);
ylim([1.6,2]);
title('Рис. 2')
figure
ezplot(s,[f(1),z]);

Миниатюры

Почему Plot не работает?
 



1



2 / 2 / 0

Регистрация: 24.06.2010

Сообщений: 39

10.11.2010, 16:45

 [ТС]

3

Точно поставила 2010b работает)) Спасибо, учла ваше предложение с выводом графиков)
Стоял 2008a..



0



1 / 1 / 0

Регистрация: 09.11.2010

Сообщений: 23

10.11.2010, 16:47

4

Не знаю как у вас, а у меня все работает, только не знаю правильно или нет!
а вообще, если Вы в графике используете переменную, «Х» то:
1) а^x -> a.^x
2) a/x -> a * 1./x
2) (a * x) * (b * x) -> (a * x) .* (b * x)
а иначе он выдаст ошибку внутренней матрицы!

Почему Plot не работает?

Почему Plot не работает?



0



128 / 127 / 10

Регистрация: 09.11.2010

Сообщений: 200

10.11.2010, 17:01

5

Цитата
Сообщение от amiraraya
Посмотреть сообщение

Вы конечно правы на счёт задачи «матричных» алгебраических действий. Перед знаками * и / требуется ставить точку .* и соответственно ./, так же справедливо и для операции возведения в степень .^

В функцию построения графика не входит переменная. В функцию передаётся символьная константа, там получается логарифм 6.



0



1 / 1 / 0

Регистрация: 09.11.2010

Сообщений: 23

10.11.2010, 17:30

6

Цитата
Сообщение от Sergik1
Посмотреть сообщение

Вы конечно правы на счёт задачи «матричных» алгебраических действий. Перед знаками * и / требуется ставить точку .* и соответственно ./, так же справедливо и для операции возведения в степень .^

В функцию построения графика не входит переменная. В функцию передаётся символьная константа, там получается логарифм 6.

если бы я не делал графики в Matlab GUI, и не провозился бы именно с этой проблемой, когда мне пришлось полностью все формулы для огроменного процесса переделывать, с огромным количеством вводных и тд. , а проблема была ТОЛЬКО в графиках, я бы промолчал



0



Солярис

Пользователь
Сообщения: 7
Зарегистрирован: Пт дек 28, 2012 11:44 pm

Окно PLOTS в MATLAB R2012b

Здравствуйте. Недавно установил версию R2012b. До этого пользовался седьмой версией матлаба. Сразу же возник вопрос, по-поводу окна PLOTS. При его выборе графики почему-то неактивны. Так и должно быть? Или, быть может, я в настройках что-то не так сделал. Подскажите пожалуйста.


lomt

Пользователь
Сообщения: 58
Зарегистрирован: Вт окт 30, 2012 2:56 pm

Сообщение lomt » Сб дек 29, 2012 10:01 am

с вашего позволения, немного расширю вопрос. Пользовался ли кто-то 12b версией, что там нового, и есть ли смысл переходить на неё, скажем, с 11b?


Солярис

Пользователь
Сообщения: 7
Зарегистрирован: Пт дек 28, 2012 11:44 pm

Сообщение Солярис » Сб дек 29, 2012 10:12 am

lomt писал(а):с вашего позволения, немного расширю вопрос. Пользовался ли кто-то 12b версией, что там нового, и есть ли смысл переходить на неё, скажем, с 11b?

Приветствую, как я понимаю вы уже использовали в работе 11b?Если да, то у меня вопрос к Вам. Вы когда нажимаете на окно PLOTS, у Вас не затемнены все виды графиков, случайно? Может так и должно быть? Вы можете выбирать любой из видов графиков? Они у Вас активны?


lomt

Пользователь
Сообщения: 58
Зарегистрирован: Вт окт 30, 2012 2:56 pm

Сообщение lomt » Сб дек 29, 2012 10:21 am

А что вы подразумеваете под окном PLOTS? Figure, в котором строится с помощью, к примеру, plot() графики?


Солярис

Пользователь
Сообщения: 7
Зарегистрирован: Пт дек 28, 2012 11:44 pm

Сообщение Солярис » Сб дек 29, 2012 10:42 am

lomt писал(а):А что вы подразумеваете под окном PLOTS? Figure, в котором строится с помощью, к примеру, plot() графики?

Да. Есть три основных окна в интерфейсе:HOME, PLOTS и APPS(они переключаются слева вверху). Так вот, когда я нажимаю на окно PLOTS, там можно выбирать базовые примеры графиков(фигур). Но, почему-то, все примеры затемнены(т. е. неактивны). Так и должно быть? Или что-то не так у меня?


sandy

Эксперт
Сообщения: 5601
Зарегистрирован: Ср сен 22, 2004 4:49 pm

Сообщение sandy » Сб дек 29, 2012 8:00 pm

lomt писал(а):А что вы подразумеваете под окном PLOTS? Figure, в котором строится с помощью, к примеру, plot() графики?

Версия 2012b имеет дурацкий «резиновый» интерфейс а-ля нынешние версии Micrtosoft Office. Имеется в виду вкладка Plots этого интерфейса.

Теперь по теме вопроса. Там же слева, вероятно, внятно написано — No variable selected. Чтобы строить графики, должна существовать переменная, в которой хранятся данные, которые вы хотите визуализировать. Ее нужно выделить в окне Workspace, тогда все будет активно.

С уважением

Александр Сергиенко


Солярис

Пользователь
Сообщения: 7
Зарегистрирован: Пт дек 28, 2012 11:44 pm

Сообщение Солярис » Сб дек 29, 2012 9:35 pm

sandy писал(а):Версия 2012b имеет дурацкий «резиновый» интерфейс а-ля нынешние версии Micrtosoft Office. Имеется в виду вкладка Plots этого интерфейса.

Теперь по теме вопроса. Там же слева, вероятно, внятно написано — No variable selected. Чтобы строить графики, должна существовать переменная, в которой хранятся данные, которые вы хотите визуализировать. Ее нужно выделить в окне Workspace, тогда все будет активно.

Теперь разобрался, спасибо Вам, Александр.


lomt

Пользователь
Сообщения: 58
Зарегистрирован: Вт окт 30, 2012 2:56 pm

Сообщение lomt » Сб дек 29, 2012 9:43 pm

sandy писал(а):

lomt писал(а):А что вы подразумеваете под окном PLOTS? Figure, в котором строится с помощью, к примеру, plot() графики?

Версия 2012b имеет дурацкий «резиновый» интерфейс а-ля нынешние версии Micrtosoft Office. Имеется в виду вкладка Plots этого интерфейса.

Теперь по теме вопроса. Там же слева, вероятно, внятно написано — No variable selected. Чтобы строить графики, должна существовать переменная, в которой хранятся данные, которые вы хотите визуализировать. Ее нужно выделить в окне Workspace, тогда все будет активно.

Спасибо, Александр Борисович. А что вообще вы скажете о новой версии Матлаба, стоит переходить на неё, или она сыренькая и нет особоых улучшений?



  • 2-D line plot

Syntax

Description

Vector and Matrix Data

example

plot(X,Y)
creates a 2-D line plot of the data in Y versus the
corresponding values in X.

  • 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,Y,LineSpec)
creates the plot using the specified line style, marker, and color.

example

plot(X1,Y1,...,Xn,Yn)
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.

example

plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)
assigns specific line styles, markers, and colors to each
xy pair. You can specify
LineSpec for some
xy pairs and omit it for others. For
example, plot(X1,Y1,"o",X2,Y2) specifies markers for the
first xy pair but not for the second
pair.

example

plot(Y) plots Y
against an implicit set of x-coordinates.

  • If Y is a vector, the
    x-coordinates range from 1 to
    length(Y).

  • If Y is a matrix, the plot contains one line
    for each column in Y. The
    x-coordinates range from 1 to the number of rows
    in Y.

If Y contains complex numbers, MATLAB® plots the imaginary part of Y versus the real
part of Y. If you specify both X and
Y, the imaginary part is ignored.

plot(Y,LineSpec)
plots Y using implicit x-coordinates, and
specifies the line style, marker, and color.

Table Data

plot(tbl,xvar,yvar)
plots the variables xvar and yvar from the
table tbl. To plot one data set, specify one variable for
xvar and one variable for yvar. To
plot multiple data sets, specify multiple variables for xvar,
yvar, or both. If both arguments specify multiple
variables, they must specify the same number of variables. (since
R2022a)

example

plot(tbl,yvar)
plots the specified variable from the table against the row indices of the
table. If the table is a timetable, the specified variable is plotted against
the row times of the timetable. (since R2022a)

Additional Options

example

plot(ax,___) displays
the plot in the target axes. Specify the axes as the first argument in any of
the previous syntaxes.

example

plot(___,Name,Value)
specifies Line properties using one or more name-value
arguments. The properties apply to all the plotted lines. Specify the name-value
arguments after all the arguments in any of the previous syntaxes. For a list of
properties, see Line Properties.

example

p = plot(___) returns a
Line object or an array of Line
objects. Use p to modify properties of the plot after
creating it. For a list of properties, see Line Properties.

Examples

collapse all

Create Line Plot

Create x as a vector of linearly spaced values between 0 and . Use an increment of π/100 between the values. Create y as sine values of x. Create a line plot of the data.

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

Figure contains an axes object. The axes object contains an object of type line.

Plot Multiple Lines

Define x as 100 linearly spaced values between -2π and . Define y1 and y2 as sine and cosine values of x. Create a line plot of both sets of data.

x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);

figure
plot(x,y1,x,y2)

Figure contains an axes object. The axes object contains 2 objects of type line.

Create Line Plot From Matrix

Define Y as the 4-by-4 matrix returned by the magic function.

Y = 4×4

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

Create a 2-D line plot of Y. MATLAB® plots each matrix column as a separate line.

Figure contains an axes object. The axes object contains 4 objects of type line.

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.

x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);

figure
plot(x,y1,x,y2,'--',x,y3,':')

Figure contains an axes object. The axes object contains 3 objects of type 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.

x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);

figure
plot(x,y1,'g',x,y2,'b--o',x,y3,'c*')

Figure contains an axes object. The axes object contains 3 objects of type line.

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.

x = linspace(0,10);
y = sin(x);
plot(x,y,'-o','MarkerIndices',1:5:length(y))

Figure contains an axes object. The axes object contains an object of type line.

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.

x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));

figure
plot(x,y,'--gs',...
    'LineWidth',2,...
    'MarkerSize',10,...
    'MarkerEdgeColor','b',...
    'MarkerFaceColor',[0.5,0.5,0.5])

Figure contains an axes object. The axes object contains an object of type line.

Add Title and Axis Labels

Use the linspace function to define x as a vector of 150 values between 0 and 10. Define y as cosine values of x.

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

Create a 2-D line plot of the cosine curve. Change the line color to a shade of blue-green using an RGB color value. Add a title and axis labels to the graph using the title, xlabel, and ylabel functions.

figure
plot(x,y,'Color',[0,0.7,0.9])

title('2-D Line Plot')
xlabel('x')
ylabel('cos(5x)')

Figure contains an axes object. The axes object with title 2-D Line Plot contains an object of type line.

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.

t = 0:seconds(30):minutes(3);
y = rand(1,7);

plot(t,y,'DurationTickFormat','mm:ss')

Figure contains an axes object. The axes object contains an object of type line.

Plot Coordinates from a Table

Since R2022a

A convenient way to plot data from a table is to pass the table to the plot function and specify the variables to plot.

Read weather.csv as a timetable tbl. Then display the first three rows of the table.

tbl = readtimetable("weather.csv");
tbl = sortrows(tbl);
head(tbl,3)
            Time            WindDirection    WindSpeed    Humidity    Temperature    RainInchesPerMinute    CumulativeRainfall    PressureHg    PowerLevel    LightIntensity
    ____________________    _____________    _________    ________    ___________    ___________________    __________________    __________    __________    ______________

    25-Oct-2021 00:00:09         46               1          84          49.2                 0                     0               29.96          4.14             0       
    25-Oct-2021 00:01:09         45             1.6          84          49.2                 0                     0               29.96         4.139             0       
    25-Oct-2021 00:02:09         36             2.2          84          49.2                 0                     0               29.96         4.138             0       

Plot the row times on the x-axis and the RainInchesPerMinute variable on the y-axis. When you plot data from a timetable, the row times are plotted on the x-axis by default. Thus, you do not need to specify the Time variable. Return the Line object as p. Notice that the axis labels match the variable names.

p = plot(tbl,"RainInchesPerMinute");

Figure contains an axes object. The axes object contains an object of type line.

To modify aspects of the line, set the LineStyle, Color, and Marker properties on the Line object. For example, change the line to a red dotted line with point markers.

p.LineStyle = ":";
p.Color = "red";
p.Marker = ".";

Figure contains an axes object. The axes object contains an object of type line.

Plot Multiple Table Variables on One Axis

Since R2022a

Read weather.csv as a timetable tbl, and display the first few rows of the table.

tbl = readtimetable("weather.csv");
head(tbl,3)
            Time            WindDirection    WindSpeed    Humidity    Temperature    RainInchesPerMinute    CumulativeRainfall    PressureHg    PowerLevel    LightIntensity
    ____________________    _____________    _________    ________    ___________    ___________________    __________________    __________    __________    ______________

    25-Oct-2021 00:00:09         46               1          84          49.2                 0                     0               29.96          4.14             0       
    25-Oct-2021 00:01:09         45             1.6          84          49.2                 0                     0               29.96         4.139             0       
    25-Oct-2021 00:02:09         36             2.2          84          49.2                 0                     0               29.96         4.138             0       

Plot the row times on the x-axis and the Temperature and PressureHg variables on the y-axis. When you plot data from a timetable, the row times are plotted on the x-axis by default. Thus, you do not need to specify the Time variable.

Add a legend. Notice that the legend labels match the variable names.

plot(tbl,["Temperature" "PressureHg"])
legend

Figure contains an axes object. The axes object contains 2 objects of type line.

Specify Axes for Line Plot

Starting in R2019b, you can display a tiling of plots using the tiledlayout and nexttile functions. Call the tiledlayout function to create a 2-by-1 tiled chart layout. Call the nexttile function to create an axes object and return the object as ax1. Create the top plot by passing ax1 to the plot function. Add a title and y-axis label to the plot by passing the axes to the title and ylabel functions. Repeat the process to create the bottom plot.

% Create data and 2-by-1 tiled chart layout
x = linspace(0,3);
y1 = sin(5*x);
y2 = sin(15*x);
tiledlayout(2,1)

% Top plot
ax1 = nexttile;
plot(ax1,x,y1)
title(ax1,'Top Plot')
ylabel(ax1,'sin(5x)')

% Bottom plot
ax2 = nexttile;
plot(ax2,x,y2)
title(ax2,'Bottom Plot')
ylabel(ax2,'sin(15x)')

Figure contains 2 axes objects. Axes object 1 with title Top Plot contains an object of type line. Axes object 2 with title Bottom Plot contains an object of type line.

Modify Lines After Creation

Define x as 100 linearly spaced values between -2π and . Define y1 and y2 as sine and cosine values of x. Create a line plot of both sets of data and return the two chart lines in p.

x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
p = plot(x,y1,x,y2);

Figure contains an axes object. The axes object contains 2 objects of type line.

Change the line width of the first line to 2. Add star markers to the second line. Use dot notation to set properties.

p(1).LineWidth = 2;
p(2).Marker = '*';

Figure contains an axes object. The axes object contains 2 objects of type line.

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.

r = 2;
xc = 4;
yc = 3;

theta = linspace(0,2*pi);
x = r*cos(theta) + xc;
y = r*sin(theta) + yc;
plot(x,y)
axis equal

Figure contains an axes object. The axes object contains an object of type line.

Input Arguments

collapse all

Xx-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.

Type of Plot How to Specify Coordinates
Single point

Specify X and Y as scalars and include a marker. For
example:

plot(1,2,"o")
One set of points

Specify X and
Y as any combination of row or
column vectors of the same length. For
example:

plot([1 2 3],[4; 5; 6])
Multiple sets of points
(using
vectors)

Specify consecutive pairs of
X and Y
vectors. For
example:

plot([1 2 3],[4 5 6],[1 2 3],[7 8 9])
Multiple sets of points
(using
matrices)

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:

plot([1 2 3],[4 5 6; 7 8 9])

If
the matrix is square, MATLAB plots one line for each column in the
matrix.

Alternatively, specify
X and Y as
matrices of equal size. In this case, MATLAB plots each column of
Y against the corresponding
column of X. For
example:

plot([1 2 3; 4 5 6],[7 8 9; 10 11 12])

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration

Yy-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.

Type of Plot How to Specify Coordinates
Single point

Specify X and Y as scalars and include a marker. For
example:

plot(1,2,"o")
One set of points

Specify X and
Y as any combination of row or
column vectors of the same length. For
example:

plot([1 2 3],[4; 5; 6])

Alternatively,
specify just the y-coordinates.
For
example:

plot([4 5 6])
Multiple sets of points
(using
vectors)

Specify consecutive pairs of
X and Y
vectors. For
example:

plot([1 2 3],[4 5 6],[1 2 3],[7 8 9])
Multiple sets of points
(using
matrices)

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:

plot([1 2 3],[4 5 6; 7 8 9])

If
the matrix is square, MATLAB plots one line for each column in the
matrix.

Alternatively, specify
X and Y as
matrices of equal size. In this case, MATLAB plots each column of
Y against the corresponding
column of X. For
example:

plot([1 2 3; 4 5 6],[7 8 9; 10 11 12])

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | categorical | datetime | duration

LineSpecLine style, marker, and color
string | character vector

Line style, marker, and color, specified as a string or character vector 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

Line Style Description Resulting Line
"-" Solid line

Sample of solid line

"--" Dashed line

Sample of dashed line

":" Dotted line

Sample of dotted line

"-." Dash-dotted line

Sample of dash-dotted line, with alternating dashes and dots

Marker Description Resulting Marker
"o" Circle

Sample of circle marker

"+" Plus sign

Sample of plus sign marker

"*" Asterisk

Sample of asterisk marker

"." Point

Sample of point marker

"x" Cross

Sample of cross marker

"_" Horizontal line

Sample of horizontal line marker

"|" Vertical line

Sample of vertical line marker

"square" Square

Sample of square marker

"diamond" Diamond

Sample of diamond line marker

"^" Upward-pointing triangle

Sample of upward-pointing triangle marker

"v" Downward-pointing triangle

Sample of downward-pointing triangle marker

">" Right-pointing triangle

Sample of right-pointing triangle marker

"<" Left-pointing triangle

Sample of left-pointing triangle marker

"pentagram" Pentagram

Sample of pentagram marker

"hexagram" Hexagram

Sample of hexagram marker

Color Name Short Name RGB Triplet Appearance
"red" "r" [1 0 0]

Sample of the color red

"green" "g" [0 1 0]

Sample of the color green

"blue" "b" [0 0 1]

Sample of the color blue

"cyan" "c" [0 1 1]

Sample of the color cyan

"magenta" "m" [1 0 1]

Sample of the color magenta

"yellow" "y" [1 1 0]

Sample of the color yellow

"black" "k" [0 0 0]

Sample of the color black

"white" "w" [1 1 1]

Sample of the color white

tblSource table
table | timetable

Source table containing the data to plot, specified as a table or a timetable.

xvarTable variables containing x-coordinates
string array | character vector | cell array | pattern | numeric scalar or vector | logical vector | vartype()

Table variables containing the x-coordinates, specified
using one of the indexing schemes from the table.

Indexing Scheme Examples

Variable names:

  • A string, character vector, or cell array.

  • A pattern object.

  • "A" or 'A' — A variable
    called A

  • ["A","B"] or {'A','B'}
    Two variables called A and
    B

  • "Var"+digitsPattern(1) — Variables named
    "Var" followed by a single digit

Variable index:

  • An index number that refers to the location of a variable in
    the table.

  • A vector of numbers.

  • A logical vector. Typically, this vector is the same length as
    the number of variables, but you can omit trailing
    0 or false
    values.

  • 3 — The third variable from the
    table

  • [2 3] — The second and third variables from
    the table

  • [false false true] — The third
    variable

Variable type:

  • A vartype subscript
    that selects variables of a specified type.

  • vartype("categorical") — All the variables
    containing categorical values

The table variables you specify can contain numeric, categorical,
datetime, or duration values. If xvar and
yvar both specify multiple variables, the number of
variables must be the same.

Example: plot(tbl,["x1","x2"],"y") specifies the table
variables named x1 and x2 for the
x-coordinates.

Example: plot(tbl,2,"y") specifies the second variable
for the x-coordinates.

Example: plot(tbl,vartype("numeric"),"y") specifies all
numeric variables for the x-coordinates.

yvarTable variables containing y-coordinates
string array | character vector | cell array | pattern | numeric scalar or vector | logical vector | vartype()

Table variables containing the y-coordinates, specified
using one of the indexing schemes from the table.

Indexing Scheme Examples

Variable names:

  • A string, character vector, or cell array.

  • A pattern object.

  • "A" or 'A' — A variable
    called A

  • ["A","B"] or {'A','B'}
    Two variables called A and
    B

  • "Var"+digitsPattern(1) — Variables named
    "Var" followed by a single digit

Variable index:

  • An index number that refers to the location of a variable in
    the table.

  • A vector of numbers.

  • A logical vector. Typically, this vector is the same length as
    the number of variables, but you can omit trailing
    0 or false
    values.

  • 3 — The third variable from the
    table

  • [2 3] — The second and third variables from
    the table

  • [false false true] — The third
    variable

Variable type:

  • A vartype subscript
    that selects variables of a specified type.

  • vartype("categorical") — All the variables
    containing categorical values

The table variables you specify can contain numeric, categorical,
datetime, or duration values. If xvar and
yvar both specify multiple variables, the number of
variables must be the same.

Example: plot(tbl,"x",["y1","y2"]) specifies the table
variables named y1 and y2 for the
y-coordinates.

Example: plot(tbl,"x",2) specifies the second variable
for the y-coordinates.

Example: plot(tbl,"x",vartype("numeric")) specifies all
numeric variables for the y-coordinates.

axTarget 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

Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN, where Name is
the argument name and Value is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.

Example: plot([0 1],[2 3],LineWidth=2)


Before R2021a, use commas to separate each name and value, and enclose

Name in quotes.

Example: plot([0 1],[2 3],"LineWidth",2)

Note

The properties listed here are only a subset. For a complete list, see
Line Properties.

ColorLine color
[0 0.4470 0.7410] (default) | RGB triplet | hexadecimal color code | "r" | "g" | "b" | …

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.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

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"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: "blue"

Example: [0
0 1]

Example: "#0000FF"

Line style, specified as one of the options listed in this table.

Line Style Description Resulting Line
"-" Solid line

Sample of solid line

"--" Dashed line

Sample of dashed line

":" Dotted line

Sample of dotted line

"-." Dash-dotted line

Sample of dash-dotted line, with alternating dashes and dots

"none" No line No line

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.

Marker Description Resulting Marker
"o" Circle

Sample of circle marker

"+" Plus sign

Sample of plus sign marker

"*" Asterisk

Sample of asterisk marker

"." Point

Sample of point marker

"x" Cross

Sample of cross marker

"_" Horizontal line

Sample of horizontal line marker

"|" Vertical line

Sample of vertical line marker

"square" Square

Sample of square marker

"diamond" Diamond

Sample of diamond line marker

"^" Upward-pointing triangle

Sample of upward-pointing triangle marker

"v" Downward-pointing triangle

Sample of downward-pointing triangle marker

">" Right-pointing triangle

Sample of right-pointing triangle marker

"<" Left-pointing triangle

Sample of left-pointing triangle marker

"pentagram" Pentagram

Sample of pentagram marker

"hexagram" Hexagram

Sample of hexagram marker

"none" No markers Not applicable

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.

Marker outline color, specified as "auto", an RGB triplet, a
hexadecimal color code, a color name, or a short name. The default value of
"auto" uses the same color as the Color
property.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

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"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Marker fill color, specified as "auto", an RGB triplet, a hexadecimal
color code, a color name, or a short name. The "auto" option uses the
same color as the Color property of the parent axes. If you specify
"auto" and the axes plot box is invisible, the marker fill color is
the color of the figure.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

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"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.

DatetimeTickFormatFormat for datetime tick labels
character vector | string

Format for datetime tick labels, specified as the comma-separated pair
consisting of "DatetimeTickFormat" and a character
vector or string containing a date format. Use the letters
A-Z and a-z to construct a
custom format. These letters correspond to the Unicode® Locale Data Markup Language (LDML) standard for dates. You
can include non-ASCII letter characters such as a hyphen, space, or
colon to separate the fields.

If you do not specify a value for "DatetimeTickFormat", then
plot automatically optimizes and updates the
tick labels based on the axis limits.

Example: "DatetimeTickFormat","eeee, MMMM d, yyyy HH:mm:ss" displays a date
and time such as Saturday, April 19, 2014
21:41:06
.

The following table shows several common display formats and
examples of the formatted output for the date, Saturday, April 19,
2014 at 9:41:06 PM in New York City.

Value of DatetimeTickFormat Example
"yyyy-MM-dd" 2014-04-19
"dd/MM/yyyy" 19/04/2014
"dd.MM.yyyy" 19.04.2014
"yyyy年 MM月
dd日"
2014年 04月 19日
"MMMM d, yyyy" April 19, 2014
"eeee, MMMM d, yyyy HH:mm:ss" Saturday, April 19, 2014 21:41:06
"MMMM d, yyyy HH:mm:ss Z" April 19, 2014 21:41:06 -0400

For a complete list of valid letter identifiers, see the Format property
for datetime arrays.

DatetimeTickFormat 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 datetime
ruler stores the format.

DurationTickFormatFormat for duration tick labels
character vector | string

Format for duration tick labels, specified as the comma-separated pair
consisting of "DurationTickFormat" and a character
vector or string containing a duration format.

If you do not specify a value for "DurationTickFormat", then
plot automatically optimizes and updates the
tick labels based on the axis limits.

To display a duration as a single number that includes a fractional
part, for example, 1.234 hours, specify one of the values in this
table.

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.

  • "dd:hh:mm:ss"

  • "hh:mm:ss"

  • "mm:ss"

  • "hh:mm"

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.

Tips

  • 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.

    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. (since R2019b)

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:

    • plot(X,Y)

    • plot(Y)

    • plot(___,LineSpec)

    • plot(___,Name,Value)

    • plot(ax,___)

  • X must be in monotonically increasing order.

  • Categorical inputs are not supported.

  • Tall inputs must be real column vectors.

  • With tall arrays, the plot function plots in iterations, progressively adding to the plot as more data is read. During the updates, a progress indicator shows the proportion of data that has been plotted. Zooming and panning is supported during the updating process, before the plot is complete. To stop the update process, press the pause button in the progress indicator.

For more information, see Visualization of Tall Arrays.

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

Usage notes and limitations:

  • 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™.

Usage notes and limitations:

  • 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

expand all

R2022b: Plots created with tables preserve special characters in axis and legend labels

When you pass a table and one or more variable names to the plot function, the axis and legend labels now display any special characters that are included in the table variable names, such as underscores. Previously, special characters were interpreted as TeX or LaTeX characters.

For example, if you pass a table containing a variable named Sample_Number
to the plot function, the underscore appears in the axis and
legend labels. In R2022a and earlier releases, the underscores are interpreted as
subscripts.

Release Label for Table Variable "Sample_Number"

R2022b

Label for the variable name "Sample_Number" in R2022b. The underscore is included in the label.

R2022a

Label for the variable name "Sample_Number" in R2022a. The N character displays as a subscript.

To display axis and legend labels with TeX or LaTeX formatting, specify the labels manually.
For example, after plotting, call the xlabel or
legend function with the desired label strings.

xlabel("Sample_Number")
legend(["Sample_Number" "Another_Legend_Label"])

R2022a: Pass tables directly to plot

Create plots by passing a table to the plot function followed by the variables you want to plot. When you specify your data as a table, the axis labels and the legend (if present) are automatically labeled using the table variable names.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Select error ora 01722 invalid number
  • Select error column lists do not match
  • Select corona as your production render first как исправить
  • Select action an error occurred while trying to copy a file
  • Segmentation fault core dumped как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии