How to remove the track of a N point matlab animation [duplicate] - matlab

This question already has answers here:
Matlab update plot with multiple data lines/curves
(2 answers)
Closed 6 years ago.
I have animated the motion of N points in 1D. The problem is that I cannot find a way to get rid of the previous plots and remove the tracks created in the motion.
function sol=Draw(N)
%N is the number of points
PointsPos=1:N
for s=1:1000
for i=1:N
PointsPos(i)=PointsPos(i)+ rand(1,1)
%The position of the point is increased.
end
for i=1:N
%loop to draw the points after changing their positions
hold on
plot(PointsPos,1,'.')
end
pause(0.005)
%here I want to delete the plots of the previous frame s
end
end

A general guideline for MATLAB procedural animation is:
Avoid creating or deleting graphical objects as much as possible in the animation loop.
Therefore, if you invoke plot image surf or delete in the animation loop, then most likely you are not doing it optimally.
Here, the best practice is to create the plot BEFORE the animation loop, then use set(plot_handle, 'XData', ...) to update the x coordinates of the plot points.
Also you should add a rand(1, N) to PointsPos, as opposed to adding rand(1, 1) N times.
So you code should look somewhat similar to the following:
function sol=Draw(N)
PointsPos=1:N
h = plot(PointsPos, ones(1, N), '.');
for s=1:1000
PointsPos=PointsPos+ rand(1,N)
set(h, 'XData', PointsPos);
pause(0.005)
end
end

If I understood your goal, then this should do what you want:
function sol = Draw(N)
steps = 1000;
% N is the number of points
PointsPos = cumsum([1:N; rand(steps-1,N)],1);
p = scatter(PointsPos(1,:),ones(N,1),[],(1:N).');
colormap lines
for s = 2:steps
p.XData = PointsPos(s,:);
drawnow
end
end
Note that:
There is no need to compute anything inside the loop, use vectorization and cumsum to calculate all the positions of the points (i.e. all the PointsPos matrix) at once.
For plotting unrelated circles, scatter would be a better choice.
Instead of using pause with some arbitrary time you can use drawnow to update your plot.

Related

Looping over subplots and holding [duplicate]

This question already exists:
Matlab subplots in loop: only shows plots in last iteration
Closed 3 years ago.
I'm trying to create a plot and layer multiple functions over each of the subplots. The output I'm getting, however, is only showing the final plot in each iteration. In other words, all subplots are filled with something, but only with the last curve that I 'added' (or at least I thought I did) -- the cyan curve. I tried using hold onin a number of different places, to no avail. Does anyone see what the problem might be?
%% Training phase
% Setting for plots
figure;
for tai = 1:length(training_algorithms)
% Create first subplot (and make sure we stay there)
subplot(3,2,tai);
% Plot the (sampled) sine function
plot(x,y,'bx');
hold on
colors = ['r', 'm', 'c'];
for nh = 1:length(num_hid)
net = networks{tai, nh}; % Load network
net.trainParam.showWindow = false; % Don't show graph
% Train network, and time training
tic;
[net, tr] = train(net, p, t);
durations(tai)=toc;
% Simulate input on trained networks (and convert to double format)
y_result = cell2mat(sim(net, p));
% Evaluate result
[slo, int, correlations{tai}] = postregm(y_result, y);
% Add network to array
networks{tai} = net;
% Plot network approximation results
plot(x,y_result,colors(nh))
ylim([-3 3])
title(training_algorithms{tai});
end
hold off
end
It looks like this has been answered already but it is also worth noting that even though you are setting the net.trainParam.showWindow property to 'false,' Matlab may still create a new figure and make it active even though it remains hidden. Then any plots you perform after that won't stack like you want unless you make the original plot active again.
For example, if you run the below code (I stripped out all of your specific functions but recreated the affect) you will see that at the end, there are 20 or so figures open but only 1 is visible. Uncommment the line towards the bottom in order to create the kind of stacked subplots you are after... Hope this helps.
Cheers.
% Training phase
% Setting for plots
f1=figure(1);
for i = 1:6
% Create first subplot (and make sure we stay there)
subplot(3,2,i);
x=0:.1:2*pi;
y=sin(x);
% Plot the (sampled) sine function
plot(x,y,'b');
hold on
colors = {'r', 'm', 'c'};
for j=1:3
f2=figure;
set(f2,'Visible','off');
y2=sin(x+j);
% Plot network approximation results
% figure(f1) % - uncommment me
plot(x,y2,colors{j})
end
hold off
end
figHandles = findobj('Type', 'figure')

How do I plot inside a for loop? Matlab

I'm trying to plot a straight line from a point in x to different values of t, thereby making a line in a for loop. But I see no lines generated in my figure in MATLAB
Following is my code:
t=linspace(0,8,11)
xs=(1.+t).^0.5
x0=xs./(1.+t)
m=size(t)
n=max(m)
hold on
for k=1:n
plot(x0(k),t(1:k),'-')
hold on
end
Thanks
You do not need the loop to perform the plot.
plot(x0,t,'-')
Will work just fine! Unless you were attempting to plot points...use scatter() for that:
scatter(x0,t)
plot() and scatter() (and most of Matlab's functions) are meant to be used with vectors, which can take some time to get used to if you are used to traditional programming languages. Just as you didn't need a loop to create the vector x0, you don't need a loop to use plot().
You are adding one point in Y axis along a line in X Axis use this code
t=linspace(0,8,11)
xs=(1.+t).^0.5
x0=xs./(1.+t)
m=size(t)
n=max(m)
hold on
for k=1:n
plot(x0(1:k),t(1:k),'-')
hold on
end
for more fun and see exactly how for is performed use this for loop
for k=1:n
pause('on')
plot(x0(1:k),t(1:k),'-')
hold on
pause(2)
end

Matlab, figures and for loops

I am trying to plot the following simple function; $y=A.*x$ with different A parameter values i.e. A=0,1,2,3 all on the same figure. I know how to plot simple functions i.e. $y=x$ by setting up x as a linspace vector so defining x=linspace(0,10,100); and I know that one can use the hold command.
I thought that one could simply use a for loop, but the problem then is getting a plot of all the permutations on one figure, i.e. I want a plot of y=t,2*t,3*t,4*t on the same figure. My attempt is as follows:
x=linspace(0,10,100);
%Simple example
Y=x;
figure;
plot(Y);
%Extension
B=3;
F=B*x;
figure;
plot(F);
%Attempt a for loop
for A= [0,1,2,3]
G=A*x;
end
figure;
plot(G);
This is how I would plot your for loop example:
figure;
hold all;
for A=[0,1,2,3]
G=A*x;
plot(G);
end
figure creates a new figure. hold all means that subsequent plots will appear on the same figure (hold all will use different colours for each plot as opposed to hold on). Then we plot each iteration of G within the loop.
You can also do it without the loop. As with most things in Matlab, removing the loop should give improved performance.
figure;
A=[0,1,2,3];
G=x'*A;
plot(G);
G is the outer product of the two vectors x and A (with x having been transposed into a column vector). plot is used to plot the columns of the 100x4 matrix G.

For loop in matlab plot

Hello i am having some problems understading basic plotting in matlab.
I can understand why you would use a for loop when plotting data?
Can anybody explain this to me?
I am making a simple linear plot. Is there any reason this should be inside a loop
If you are making a simple plot there is virtually no reason to use a loop.
If you check doc plot you will find that plot can take some vectors as input, or even matrices for more interesting situations.
Example:
x=0:0.01:1;
y=sin(x);
plot(x,y)
No there is no need in Matlab to use a for loop for plotting. If you are looking for a simple linear plot your code could look like this:
x=1:100;
y=3*x+4;
plot(x,y)
As you see there is no for loop needed. Same goes for nearly all plots and visualization.
A possible reason to use a for loop to plot thing may be having several data to plot in a single matrix. Say you have two matrix Ax (MxN) and Ay (MxN) where N the length of each data and M is the amount of different data wanted to plot. For example like in this case N is 201 and M is 3:
% Create Ax and Ay
Ax=meshgrid(0:0.1:20,1:3);
Ay=zeros(size(Ax));
% Sinusoidals with different frequencies
for k=1:3
Ay(k,:)=sin(k.*Ax(k,:));
end
% create colours
colorVec = hsv(3);
% Plot
hold on
for k=1:3
plot(Ax(k,:),Ay(k,:),'Color',colorVec(k,:))
end
hold off
You get:

Real time plot in MATLAB

I'm very new to MATLAB and I was trying to display a real time plot of some calculations. I have an N sized vector and I work with m values at a time (say m = N/4), so I want to plot the first m values and then as soon as the second m values are calculated have them replace the first plot.
My approach was as follows:
for i=1:N,
...
//compute m
...
plot(m);
end;
but it fails to update the plot in every loop and waits for all the loops to finish to plot the data. My question is: Should I use another function instead of plot or could I add some delay in each loop?
I think there must be a way I'm not aware of for updating the plot instead of re-plotting it every time.
As Edric mentioned, you'll definitely want to include a drawnow command after the call to plot to force an update of the graphics. However, there is a much more efficient and smoother method to animate plots that doesn't involve recreating the entire plot each time. You can simply initialize your plot, capture a handle to the plot object, then modify the properties of that object in your loop using the set command. Here's an example:
hLine = plot(nan); % Initialize a plot line (which isn't displayed yet
% because the values are NaN)
for i = 1:N % Loop N times
...
% Compute m here
...
set(hLine, 'YData', m); % Update the y data of the line
drawnow % Force the graphics to update immediately
end
In addition, before your loop and after the call to plot you can set a number of axes properties, like the axes limits, etc., if you want the axes to stay fixed and not change their appearance with each new vector m that is plotted.
You can add a call to DRAWNOW to force the plot to update. See the reference page. Note that DRAWNOW causes the graphics event queue to be flushed, which may cause callbacks etc. to be executed.