Separate initialization and display of plot - matlab

What is a proper way to separate the initialization and the display of plots in Matlab? (I mean plots in a wide sense here; could be plot, plot3, scatter etc.) To give a concrete example, I have a pretty complex 3D visualization that uses sphere and mesh to draw a static sphere mesh and then scatter3 to plot a moving trajectory on the sphere. To be able to do this in real time I have implemented some simple optimizations, such as only updating the scatter3 object each frame. But the code is a bit messy, making it hard to add additional features that I want, so I would like improve code separation.
I also feel like it might sometimes be useful to return some kind of plot object from a function without displaying it, for example to combine it with other plots in a nice modular way.
An example of what I have in mind would be something like this:
function frames = spherePlot(solution, options)
% Initialize sphere mesh and scatter objects, configure properties.
...
% Configure axes, maybe figure as well.
...
% Draw sphere.
...
if options.display
% Display figure.
end
for step = 1:solution.length
% Update scatter object, redraw, save frame.
% The frames are saved for use with 'movie' or 'VideoWriter'.
end
end
Each step might also be separated out as a function.
So, what is a neat and proper way to do stuff like this? All documentation seems to assume that one wants to display everything right away.

For example
% some sample data
N = 100;
phi = linspace(-pi, pi, N);
theta = linspace(-pi, pi, N);
f = #(phi, theta) [sin(phi).*cos(theta); sin(phi).*sin(theta); cos(phi)];
data = f(phi, theta);
% init plot
figure(1); clf
plot3(data(1,:), data(2,:), data(3,:)); % plot path, not updated
hold on
p = plot3([0 data(1,1)], [0 data(2,1)], [0 data(3,1)]); % save handle to graphics objects to update
s = scatter3(data(1,1), data(2,1), data(3,1), 'filled');
axis equal
xlabel('x'); ylabel('y'); zlabel('z');
t = title('first frame'); % also store handle for title or labels to update during animation
% now animate the figure
for k = 1:N
p.XData = [0 data(1,k)]; % update line data
p.YData = [0 data(2,k)];
p.ZData = [0 data(3,k)];
s.XData = data(1,k); % update scatter data
s.YData = data(2,k);
s.ZData = data(3,k);
t.String = sprintf('frame %i', k); % update title
drawnow % update figure
end
Basically you can update all values for a graphics handle, in this case 'p' and 's'. If you open the matlab doc for plot or plot3 you will find a link to all properties of that primitive: e.g. Line Properties. Similar documentation pages exist for scatter/imagesc etc.
So the general idea is to first create a figure with the first frame, save the handles to the objects you would like to update (p = plot(...), and then enter a loop in which you update the required property of that graphics object (e.g. p.Color = 'r', or p.XData = ...).

Related

How to update / animate a complicated figure in MATLAB?

I need to animate a complex figure consisting of a chain of rectangles, forming an arm.
Here is an example of how this arm looks like when not animated :
To animate this figure, I made the following code :
function renderFrame(fig, data)
hold(ax, 'on'); % Need to hold so that new elements of the arm add themselves
showMembers(fig, data); % Create patches and rotate them to the right angle to create members
showJoints(fig, data); % Draw circles at the joints betwwen the members. Use the width of rectangle members
drawnow;
hold(ax, 'off'); % Next rendering will replace this one; No need to hold
end
function rotateMember(fig, data, iMember, rotAngle)
for iAngle = 1:rotAngle
updateMemberAngle(data, i, 1); % Change thew data so the i-th member rotates by 1
renderFrame(fig); % Show frame after the data was changed
end
end
function main()
fig = figure;
ax = gca;
axis(ax, 'equal');
setAxis(data); % Set axis limits and create axis arrows with totalLength of the arm
renderFrame(ax, data);
rotateMember(fig, data, 3, 90); % Rotate 3rd member by 90 degrees
end
main()
But the frames of my animation doesn't clear at all. It results in this figure :
What am I doing wrong ? Is there a way to plot complicated figures with multiple parts and to animate it, by clearing frame ?
I looked into using newplot and nextplot, but MATLAB's documentation on the subject is incomplete, as always. I also tried creating graphic objects and then setting the data at each iteration, but it rejects an exception every time the figure is deleted since "graphics objects are deleted".
It seems to me as if in your approach, you're not erasing the plot when drawing the next frame. Maybe calling cla() prior to drawing the next frame would make it work? However, this may produce a flickering behavior if the redrawing is done in the wrong order.
I suggest taking a look at animation techniques in Matlab to see three different ways to produce animations.
Found a way to clear the axis childrens, except the two axis quivers (arrows).
Here is a code that works properly:
function renderFrame(renderAxes, data)
% CHECK IF THERE ARE MORE GRAPHIC OBJECTS THAN ONLY THE QUIVERS
if ~(length(renderAxes.Children) == 2)
% DELETE EVERYTHING EXCEPT THE AXIS QUIVERS THAT WERE RENDERED AT THE BEGINNING
% MATLAB ADDS NEW GRAPHIC OBJECTS TO THE BEGINNING OF AX.CHILDREN
delete(renderAxes.Children(1:length(renderAxes.Children)-2))
end
showMembers(renderAxes, data); % Create patches and rotate them to the right angle to create members
showJoints(renderAxes, data); % Draw circles at the joints betwwen the members. Use the width of rectangle members
drawnow;
end
function rotateMember(ax, data, iMember, rotAngle)
for iAngle = 1:rotAngle
updateMemberAngle(data, i, 1); % Change thew data so the i-th member rotates by 1
renderFrame(ax, data); % Show frame after the data was changed
end
end
function main()
fig = figure;
ax = gca;
axis(ax, 'equal');
% HOLD AXES AT THE BEGINNING OF THE SCRIPT
hold(ax, 'on');
setAxis(data); % Set axis limits and create axis arrows with totalLength of the arm
renderFrame(ax, data);
rotateMember(ax, data, 3, 90); % Rotate 3rd member by 90 degrees
end
main()

How can I reduce the number of mesh lines shown in a surface plot?

I've found this answer, but I can't complete my work. I wanted to plot more precisely the functions I am studying, without overcoloring my function with black ink... meaning reducing the number of mesh lines. I precise that the functions are complex.
I tried to add to my already existing code the work written at the link above.
This is what I've done:
r = (0:0.35:15)'; % create a matrix of complex inputs
theta = pi*(-2:0.04:2);
z = r*exp(1i*theta);
w = z.^2;
figure('Name','Graphique complexe','units','normalized','outerposition',[0.08 0.1 0.8 0.55]);
s = surf(real(z),imag(z),imag(w),real(w)); % visualize the complex function using surf
s.EdgeColor = 'none';
x=s.XData;
y=s.YData;
z=s.ZData;
x=x(1,:);
y=y(:,1);
% Divide the lengths by the number of lines needed
xnumlines = 10; % 10 lines
ynumlines = 10; % 10 partitions
xspacing = round(length(x)/xnumlines);
yspacing = round(length(y)/ynumlines);
hold on
for i = 1:yspacing:length(y)
Y1 = y(i)*ones(size(x)); % a constant vector
Z1 = z(i,:);
plot3(x,Y1,Z1,'-k');
end
% Plotting lines in the Y-Z plane
for i = 1:xspacing:length(x)
X2 = x(i)*ones(size(y)); % a constant vector
Z2 = z(:,i);
plot3(X2,y,Z2,'-k');
end
hold off
But the problem is that the mesh is still invisible. How to fix this? Where is the problem?
And maybe, instead of drawing a grid, perhaps it is possible to draw circles and radiuses like originally on the graph?
I found an old script of mine where I did more or less what you're looking for. I adapted it to the radial plot you have here.
There are two tricks in this script:
The surface plot contains all the data, but because there is no mesh drawn, it is hard to see the details in this surface (your data is quite smooth, this is particularly true for a more bumpy surface, so I added some noise to the data to show this off). To improve the visibility, we use interpolation for the color, and add a light source.
The mesh drawn is a subsampled version of the original data. Because the original data is radial, the XData and YData properties are not a rectangular grid, and therefore one cannot just take the first row and column of these arrays. Instead, we use the full matrices, but subsample rows for drawing the circles and subsample columns for drawing the radii.
% create a matrix of complex inputs
% (similar to OP, but with more data points)
r = linspace(0,15,101).';
theta = linspace(-pi,pi,101);
z = r * exp(1i*theta);
w = z.^2;
figure, hold on
% visualize the complex function using surf
% (similar to OP, but with a little bit of noise added to Z)
s = surf(real(z),imag(z),imag(w)+5*rand(size(w)),real(w));
s.EdgeColor = 'none';
s.FaceColor = 'interp';
% get data back from figure
x = s.XData;
y = s.YData;
z = s.ZData;
% draw circles -- loop written to make sure the outer circle is drawn
for ii=size(x,1):-10:1
plot3(x(ii,:),y(ii,:),z(ii,:),'k-');
end
% draw radii
for ii=1:5:size(x,2)
plot3(x(:,ii),y(:,ii),z(:,ii),'k-');
end
% set axis properties for better 3D viewing of data
set(gca,'box','on','projection','perspective')
set(gca,'DataAspectRatio',[1,1,40])
view(-10,26)
% add lighting
h = camlight('left');
lighting gouraud
material dull
How about this approach?
[X,Y,Z] = peaks(500) ;
surf(X,Y,Z) ;
shading interp ;
colorbar
hold on
miss = 10 ; % enter the number of lines you want to miss
plot3(X(1:miss:end,1:miss:end),Y(1:miss:end,1:miss:end),Z(1:miss:end,1:miss:end),'k') ;
plot3(X(1:miss:end,1:miss:end)',Y(1:miss:end,1:miss:end)',Z(1:miss:end,1:miss:end)','k') ;

How do I reach first and second plots from bode()

I know how to create the Bode plots with bode() function. If I want to overlap two or more systems frequency responses, I use
bode(sys1,sys2,...)
or
hold on
When I want to reach the plot in order to put a legend with text(), for instance, is easy to reach the second plot. Something like the figure pointer always returns to the second plot (phase graph).
i.e., if try these lines:
G = tf([1],[1 6]); figure(1); bode(G); text(10,-20,'text');
G = tf([1],[1 6]); figure(2); bode(G); text(10,-20,'text');
when I return to the first figure, with figure(1), and try
figure(1); text(10,-20,'text')
legend is displayed in the second plot (Phase plot)
I try these other lines:
P = bodeoptions; % Set phase visiblity to off
P.PhaseVisible = 'off';
G = tf([1],[1 6]);
figure(1); bode(G,P); text(10,-20,'text');
figure(1); text(10,-20,'text');
As you can see, even I turn off the phase plot visiblity, the legend is not displayed.
Essentialy, my question is, how do I reach first and second plots, one by one? I tried with subplot(), but it is pretty clear this is not the way Matlab traces these plots.
Thanks in advance.
It all comes to getting into upper plot, since after bodeplot command the lower one is active. Intuitively one would want to call subplot(2,1,1), but this just creates new blank plot on top of if. Therefore we should do something like this:
% First, define arbitrary transfer function G(s), domain ww
% and function we want to plot on magnitude plot.
s = tf('s');
G = 50 / ( s*(1.6*s+1)*(0.23*s+1) );
ww = logspace(0,3,5000);
y = 10.^(-2*log10(ww)+log10(150));
hand = figure; % create a handle to new figure
h = bodeplot(G,ww);
hold on;
children = get(hand, 'Children') % use this handle to obtain list of figure's children
% We see that children has 3 objects:
% 1) Context Menu 2) Axis object to Phase Plot 3) Axis object to Magnitude Plot
magChild = children(3); % Pick a handle to axes of magnitude in bode diagram.
% magChild = childern(2) % This way you can add data to Phase Plot.
axes(magChild) % Make those axes current
loglog(ww,y,'r');
legend('transfer function','added curve')
you can get magnitude and phase data separately for each system using:
[mag,phase] = bode(sys,w)
now you can use subplot or plot to plot the diagram you want.
The only solution I was able to perform is taking into account axis position. It is not very clean but it works.
Here is the code to select mag plot:
ejes=findobj(get(gcf,'children'),'Type','axes','visible','on');
posicion=get(ejes,'pos');
tam=length(posicion);
for ii=1:tam
a=posicion{ii}(2);
vectorPos(ii)=a;
end
[valorMax,ind]=max(vectorPos); % min for choosing the phase plot
axes(ejes(ind))

Coloring Different Models in Model Array Plots (Matlab)

I would like to visualize different responses of different systems in a single plot with Matlab's control toolbox, and to colorize the various curves so it is easy to differentiate between the different systems.
The response plots are easily created using the control toolbox - e.g. step response (using step), response to an arbitrary input (using lsim), etc.
When using separate model objects for different systems, It's easy to create multi-color plots, e.g., for a step response: step(Sys1, 'b', Sys2, 'r') would give one blue curve and one red cure, if Sys1 and Sys2 are both a single system model.
However, if plotting a model array, there's no way to differentiate between the various curves that belong to the same array. E.g.: step(SysArray, 'b') would make all curves blue. step(Sys,'b','r') is invalid - so no easy way to specify various colors.
Also, using the "Edit Plot" tool, selecting one curve effectively selects all curves, and any changes to the properties (e.g. line color) would affect all curves.
Is there any way to control the properties of each curve separately?
There's no built-in function to do this, so you have to roll your own functionality
% Create n-by-3 array of colours to use
coloursArray = rand(numel(stackedSystems),3); % for this example put in random colours
% Do the plot
step(stackedSystems);
title('My custom title');
grid on
% Change colours
ha = findobj(gcf,'type','axes','visible','on'); % Get handles of all axes (for MIMO responses)
for jdx = 1:numel(ha)
hl = findobj(ha(jdx),'type','line','visible','on'); % Get handles to all lines
for idx = 1:numel(hl)
set(hl(idx),'Color',coloursArray(idx,:)); % Change the colour
end
end
#Phil Goddard
There's no built-in function to do this, so you have to roll your
own functionality
% Create n-by-3 array of colours to use
coloursArray = rand(numel(stackedSystems),3); % for this example put in random colours
% Do the plot
step(stackedSystems);
title('My custom title');
grid on
% Change colours
ha = findobj(gcf,'type','axes','visible','on'); % Get handles of all axes (for MIMO responses)
for jdx = 1:numel(ha)
hl = findobj(ha(jdx),'type','line','visible','on'); % Get handles to all lines
for idx = 1:numel(hl)
set(hl(idx),'Color',coloursArray(idx,:)); % Change the colour
end
end
Thanks for the code!
Here are some slight changes to work better with model sampling through parameter variation, including the colorbar.
I was hoping it would also work with pzmap, for example, but it creates 2*n lines (poles and zeros), so it would need a bit more work.
function colorSamplingPlot(values,var)
% values is an array with parameter value assigned to each curve
% var is a string for the colorbar label
n = numel(findobj(gca,'type','line','visible','on'));
% Create n-by-3 array of colours to use
coloursArray = colormap(jet(n));
% Change colours
% Get handles of all axes (for MIMO responses)
ha = findobj(gcf,'type','axes','visible','on');
for jdx = 1:numel(ha)
% Get handles to all lines
hl = findobj(ha(jdx),'type','line','visible','on');
for idx = 1:numel(hl)
% Change the color; inverted color order to match colorbar
set(hl(idx),'Color',coloursArray(numel(hl)-idx+1,:));
end
end
colorbar;
caxis([min(values),max(values)]);
hcb = colorbar;
hcb.Label.String = vars;
end

Trying to make MATLAB's figure stop 'blinking'

So I have a simple loop in MATLAB that does the following:
for p = 1:100
x = 4.*randn(1,100);
y = 7.*randn(1,100);
figure(1)
plot(randn(1,100));
figure(2);
plot(randn(1,100));
end
The x and y are made up, but that is the jist of it. Anyway, when I run this code, not surprisingly, MATLAB will make two figures and plot accordingly. The problem is, I get a sort of 'blinking' between figures when I do this, and it makes the quality of seeing x and y evolve over time poorer.
I discovered a way to make one of the plots smoother like this:
figure(1);
for p = 1:100
x = 4.*randn(1,100);
y = 7.*randn(1,100);
plot(randn(1,100));
drawnow
end
If I do this, then of course figure(1) will plot very smoothly showing x nicely, without figure(1) 'blinking' between plots, but now I cant show figure(2) or y!
How can I plot both those quantities on different figures (not subplots) smoothly without 'blinking'?
EDIT:
Thanks Geodesic for your answer, the solution works, however there is a subtlety that I did not think would be an issue, however it is.
1) I am unable to use 'imagesc' with this solution.
For example,
figure(1);
aone = axes;
figure(2);
atwo = axes;
for p = 1:100
x = 4.*randn(1,100);
y = 7.*rand(10,100);
plot(aone,x);
drawnow;
imagesc(atwo,y);
drawnow;
end
In this case the part with imagesc(atwo, y) crashes.
Your flicker is because you're generating each figure window again and again through the loop, which is forcing the window to come to the foreground each time. Generate the figures first, attach some axes to them, and plot your data to each axis like so:
figure(1);
aone = axes;
figure(2);
atwo = axes;
for p = 1:100
x = 4.*randn(1,100);
y = 7.*randn(1,100);
plot(aone,randn(1,100));
drawnow;
imagesc(y,'Parent',atwo);
drawnow;
end
Edit: functions like plot take an axis argument directly, but imagesc does not. In this particular case you'll need to send a Property Name/Value pair in as an argument. The 'Parent' of the image generated will be our axis atwo (see above).
For p = 1, create the plots you need, using the plot command or the imagesc command. Keep the handle of the resulting graphics object by getting an output argument: for example h = plot(.... or h = imagesc(..... This will be a Handle Graphics lineseries or image object, or something else, depending on the particular plot type you create.
For p = 2:100, don't use the plotting commands directly, but instead update the relevant Data properties of the original Handle Graphics object h. For example, for a lineseries object resulting from a plot command, set its XData and YData properties to the new data. For an image object resulting from an imagesc command, set its CData property to the new image.
If necessary, call drawnow after updating to force a flush of the graphics queue.