User:MikeSkyHigh/'''Matlab'''/Plot Command

From Wikibooks, open books for an open world
Jump to navigation Jump to search
%% Plotting large amout of graphs using for loop
Xlabel ={'t (s)','force (N)'};
Ylabel = {'x (m)','Velocity (m/s)'};
for i=1:2
    figure(i)
    xlabel(Xlabel(i));
    ylabel(Ylabel(i));
end

%% Plot log-log scale
x = 1:10;
y = 2:11;
plot(x,y,'r:o'); % plot the dotted line with highlighted circle points
bar(x,y); % plot the histogram 
% loglog, logplot in x,y,
loglog(x,y); % plot the log-log scale
semilogy(x,y); % plot the log scale only in y 
semilogx(x,y); % likewise, plot the log scale in x


%% Plotting phase portrait

% Solution a)
[x1,x2]= meshgrid(-0.5:0.05:0.5,-0.5:0.05:0.5); % create a 2D plane ponts, note, x1 is 21x21, x2 is also 21x21
xd1 = -x1-2*x2.*x1.^2+x2;
xd2 = -x1-x2;
quiver(x1,x2,xd1,xd2,'r'); % Velocity plot, which displays velocity vectors as arrows with components (xd1,xd2) at the points (x1,x2).
axis tight;

% Solution b)
f = @(t,x) [x(2);-x(1)+x(2)*(1-3*x(1)^2-3*x(2)^2)];
vectfield(f,-0.5:0.05:0.5,-0.5:0.05:0.5);
%
function vectfield(func,y1val,y2val,t)
if nargin==3 % numer of function input argument
  t=0;
end
n1=length(y1val);
n2=length(y2val);
yp1=zeros(n2,n1);
yp2=zeros(n2,n1);
for i=1:n1
  for j=1:n2
    ypv = feval(func,t,[y1val(i);y2val(j)]); % function evaluate
    yp1(j,i) = ypv(1);
    yp2(j,i) = ypv(2);
  end
end
quiver(y1val,y2val,yp1,yp2,'r');
axis tight;
end
%

%% Merge two plots as two subplots in a single figure
% make sure, the figures are at the same directory of your workspace
% when load the figures, dont close them, just leave them open
% Load saved figures
c=hgload('MyFirstFigure.fig');
k=hgload('MySecondFigure.fig');
% Prepare subplots
figure
h(1)=subplot(1,2,1);
h(2)=subplot(1,2,2);
% Paste figures on the subplots
copyobj(allchild(get(c,'CurrentAxes')),h(1));
copyobj(allchild(get(k,'CurrentAxes')),h(2));

%% Extract data from various plots 
% open files and extract all the data
files = {'a_21.fig','a_23.fig','a_24.fig','a_32.fig','a_34.fig','a_42.fig','a_43.fig'};
[~,n]=size(files);
for i = 1:n
    f = open(files{i});
    h = gca; % get current figure handle
    dataObjs = get(h, 'Children'); %handles to low-level graphics objects in axes
    xdata{i} = get(dataObjs, 'XData');  %data from low-level grahics objects
    ydata{i} = get(dataObjs, 'YData');
    zdata{i} = get(dataObjs,'ZData');
    close(f);
end

%% Matlab plot help site
web('https://www.mathworks.com/help/matlab/ref/plot.html');