How can I make this animation faster on MatLAB - matlab

This is the code. I need help making the animation faster.
write the code to make a ball bounce back and forth between to walls. The ball bounces in the form of cos2 (𝜃) where θ goes from 0˚ to 360˚ with a length of 1000.
height of the ball is 28 inches from the center.
distance between the two walls is 30 inches.
radius of the ball is 1 inch
the ball will bounce back and forth 20 times
Code Block:
r = 1;
hmax = 28;
n = 1000;
h = linspace(0,hmax,n);
t = linspace(0,360,n);
k = 0;
pt = 1/6000;
x = zeros(length(h),length(t));
vx = x;
y = x;
vy = y;
a = r+h;
b = r+hmax/2*(cosd(t).^2)+hmax/2;
for i = 1:n
x(i,:) = a(i)+r.*cosd(t);
y(i,:) = b(i)+r.*sind(t);
vx(i,:) = r+r.*cosd(t);
vy(i,:) = r+h.*sind(t);
end
figure(3)
ball_bounce1= plot(x(1:500:end),y(1:500:end),'c','linewidth',3);
axis([-1 31 -1 31])
grid on
while k < 10
if rem(k,2) == 0
for i = 1:n
set(ball_bounce1,'XData',x(i,:),'YData',y(i,:));
pause(pt)
end
end
if k > 10
break
end
end

*Just Something That Might be Useful:
Something that may or may not be interesting to you is using an animated line with a marker representing the ball. This script follows the absolute, abs() of a cosine path. The cosine frequency can also be adjusted by changing 2*pi within the line:
y = Amplitude.*abs(cos(linspace(0,2*pi,Number_Of_Samples))) + Ball_Offset;
This script uses the drawnow to repeateadly draw new points that are queued/added by the addpoints() function.
GIF of Ball Movement (a lot smoother in MATLAB):
Script:
clf;
Animated_Plot = animatedline('MaximumNumPoints',1,'Marker','o','MarkerSize',10);
Amplitude = 28;
Wall_Distance = 30;
Number_Of_Samples = 500;
Ball_Offset = 0.4;
axis([0 Wall_Distance 0 Amplitude+0.2*Amplitude]);
xlabel("Position Between Wall 0 and Wall 30"); ylabel("Amplitude");
title("Ball Movement");
x = linspace(0,Wall_Distance,Number_Of_Samples);
y = Amplitude.*abs(cos(linspace(0,2*pi,Number_Of_Samples))) + Ball_Offset;
%Mirroring and repeating%
x = [x flip(x)];
y = [y flip(y)];
x = repmat(x,1,20);
y = repmat(y,1,20);
for Point = 1: length(x)
addpoints(Animated_Plot, x(Point), y(Point));
drawnow
end
Ran using MATLAB R2019b

Reduce number of vertices of ball. You are drawing 1000 segments to draw a circle, 16 or 32 segments would be enough for that. To do so, you need x and y matrices should be m by n, where m is the number of time slices and n is the number of segments.
Firs step is to define two h and two t vectors, h1 and t1 with m elements, and h2 and t2 with n elements. After doing so, the animation runs pretty smooth here.
And as a side note, I think your movement modelling is wrong. The ball in your code moves like top figure, I believe it should go like the bottom one:

Related

Simulating a ship sailing in water wave in Matlab

I have a project in which I have to simulate a ship which is sailing in a water wave. I have decided to do it in by 3D surface plot. I have created water waves but I'm having trouble making the ship which should sit right at the centre of the plot. Following is my water wave simulation code:
clc; clear all ;
x_l = -20;
x_r = 20;
y_l = -20;
y_r = 20;
ds = 0.5;
A = 1;
k = 1;
dt = 0.05;
w = 1;
x = [x_l:ds:x_r];
y = [y_l:ds:y_r];
[X,Y] = meshgrid(x,y);
for i = 1:100
Z = A*sin(k*Y+(w*i/2));
CO(:,:,1) = 0.3*ones((y_r-y_l)/ds + 1) + 0.3*cos(k*Y+(w*i/2));
CO(:,:,2) = 0.3*ones((y_r-y_l)/ds + 1) + 0.3*cos(k*Y+(w*i/2));
CO(:,:,3) = 0.7*ones((y_r-y_l)/ds + 1) + 0.3*cos(k*Y+(w*i/2));
surf(X,Y,Z,CO);
hold on;
shading interp;
xlim([x_l x_r]);
ylim([y_l y_r]);
zlim([y_l y_r]);
Zc = sqrt(X.^2+Y.^2);
surf(X,Y,Zc);
shading interp;
hold off;
drawnow;
pause(dt);
end
Please guide me in the right direction if I'm doing this in the wrong way.
I just made a simple model of a sailing boat that is made up of quads. This allows us to use the surf function to draw it too. This should just serve as a starting point to see how you could do it. But keep in mind that this is probably not the best way of doing it. As a comment already mentioned, MATLAB is really not the best software for this, Blender is probably a way better option, but still we can make a nice little ship.
The first step is creating the fixed model in a local coordinate system. The NaNs are just to separate the different components of the ship, because otherwise we would have additional quads connecting e.g. the hull to the sails that would look out of place. (If it is unclear, just replace them with some arbitrary coordinates to see what is happening.)
Then to give it some movement, we have to incorporate the temporal component. I just added a slight rocking motion in the y-z plane as well as a little bouncing in the z-direction to give it the look of a ship moving through waves. I made sure to use the same frequency w/2 as you already used for the waves. This is important to make the boat to apper to rock with the waves.
clc; clear all ;
x_l = -20;
x_r = 20;
y_l = -20;
y_r = 20;
ds = 0.5;
A = 1;
k = 1;
dt = 0.05;
w = 1;
x = [x_l:ds:x_r];
y = [y_l:ds:y_r];
[X,Y] = meshgrid(x,y);
%sailboat
U = 0.7*[0,-1,-1,1,1,0;...%hull
0,0,0,0,0,0; NaN(1,6);...
0,0,NaN,0,0,NaN; %sails
0,-1,NaN,0,0,NaN];
V = 0.7*[3,1,-3,-3,1,3;%hull
1,1,-2,-2,1,1; NaN(1,6);...
3,0,NaN,0,-3,NaN; %sails
3,-1,NaN,0,-3,NaN];
W = 0.7*[1,1,1,1,1,1;%hull
0,0,0,0,0,0; NaN(1,6);...
2,6,NaN,7,2,NaN; %sails
2,2,NaN,2,2,NaN];
H = ones(2,6);
S = ones(3,3);
C = cat(3,[H*0.4;S*1,S*1],[H*0.2;S*0.6,S*0],[H*0;S*0.8,S*0]);
for i = 1:100
clf;
hold on;
Z = A*sin(k*Y+(w*i/2));
CO(:,:,1) = 0.3*ones((y_r-y_l)/ds + 1) + 0.3*cos(k*Y+(w*i/2));
CO(:,:,2) = 0.3*ones((y_r-y_l)/ds + 1) + 0.3*cos(k*Y+(w*i/2));
CO(:,:,3) = 0.7*ones((y_r-y_l)/ds + 1) + 0.3*cos(k*Y+(w*i/2));
surf(X,Y,Z,CO);
xlabel('x'); ylabel('y');
% rocking the boat
angle = 0.5*cos(w*i/2); %control rocking
Vs = V*cos(angle) - W*sin(angle);
Ws = V*sin(angle) + W*cos(angle) + 0.4 + 0.8*cos(w*(i - 0.5 * 2*pi)/2);%control amplitude
surf(U,Vs,Ws,C);
camproj('perspective');
xlim([x_l x_r]);
ylim([y_l y_r]);
zlim([y_l y_r]);
Zc = sqrt(X.^2+Y.^2);
%surf(X,Y,Zc);
%view([-100,20])
az = interp1([1,100],[-30, -120],i);
el = interp1([1,100],[1,30],i);
view([az,el]);
axis([-20,20,-20,20,-20,20]*0.5);
shading interp;
hold off;
drawnow;
pause(dt);
end
EDIT: The key to creating these "models" is knowign how surf works: Given some matrices X,Y,Z, each 2x2 submatrix of these matrices define the vertices of a quadrilateral. So the idea is decomposing our models into quadrilaterals (and adding NaN in this matrix where we do not want any quadrilaterals in between). Check out following snippet that shows just the hull and the quadrilaterals involved. The displayed numbers show the index of the coordinates of the corresponding points in the coordinate matrices U,V,W. I added a small number e that pulls the seams apart so that you can actually see the quadrilaterals. Set it to 0 to see the original shape:
e = 0.2; %small shift to visualize seams
%sailboat
U = 0.7*[0-e,-1-e,-1-e,1+e,1+e,0+e;...%hull
0-e,0-e,0-e,0+e,0+e,0+e];
V = 0.7*[3+e,1,-3,-3,1,3+e;%hull
1+e,1,-2,-2,1,1+e];
W = 0.7*[1,1,1,1,1,1;%hull
0,0,0,0,0,0];
surf(U,V,W);
axis equal
view([161,30])
hold on
for i=1:2
for j=1:6
text(U(i,j),V(i,j),W(i,j),[num2str(i),',',num2str(j)]); %plot indices of points
end
end
xlabel('U')
ylabel('V')
zlabel('W')
title('i,j refers to the point with coordinates (U(i,j),V(i,j),W(i,j))')
hold off

Animating circles, based on ODE-solver output in Matlab [duplicate]

I have a ball with these two equations:
x(t) = v0*cos(α)*t and
y(t) = h + v0*sin(α)*t− 1/2 gt^2 , where t ∈ [0,t final] is the time variable, h is the height, v0 is the initial speed, α is the angle made by v0 with the horizontal, g = 9.8 m/s^2. The floor is at y(x) = 0.
I need to draw a small animation of the ball moving on the plot. I now I should use for, plot, drawnow, but I don't know how to do it.
Can you tell me how to obain this animation?
First, here are some test variables to start with, including the acceleration due to gravity:
g = 9.8; %// m/s^2
v0 = 2; %// m/s
alpha = pi/6; %// Radians
h = 30; %// Start at 30 metres
t_final = 4.5; %// Seconds
t_vector = 0 : 0.01 : t_final;
t_vector in the last line of code creates a vector of points from the initial time of t = 0 up until our ending time in steps of 0.01. With these defined, our job is to go through each of these points in our vector and plot our ball. Next, let's create anonymous functions for each x and y to make our plotting easier:
x = #(t) v0*cos(alpha)*t;
y = #(t) h + v0*sin(alpha)*t - 0.5*g*t.^2;
What you can do next is use a for loop and go through each value of t_vector up until t_final and plot the individual point. You should probably make the point big so we can actually see what the ball looks like:
close all;
figure; hold on;
for t = t_vector
plot(x(t), y(t), 'b.', 'MarkerSize', 16);
axis([0 t_final 0 h]);
pause(0.01);
end
The above code will first close any figures we have open, spawn a new figure and use hold on so that we can call plot multiple times and append points to the graph without it erasing each time. Then, for each point in time, we plot the location on the graph as a blue dot, then make the size of the dot 16. We also make sure that the axis doesn't automatically adjust itself by enforcing that the x values are restricted between t = 0 up to t = t_final. We also restrict the y values from y = 0 up to the initial starting height, which is 30 in my example. At each point, we pause by 0.01 ms so you can see the drawing of the points.
As a bonus, this is what the figure looks like as an animated gif:

How to generate random positions with distance between them inside the hexagon?

I am trying to create N random pairs of points (N = 50) of a given distances, inside a 500 meters hexagon. The distance D created by using (dmax - dmin).*rand(N,1) + dmin, with dmin = 10 and dmax = 100 in Matlab. I understant that the first I have to generate a set of points ([x1 y1]) that have at least distance D from the main hexagon border, then generate the second set of points ([x2 y2]) that have exact distance D from the first set. But sometime I got the problem with the second point outside of hexagon, because if the first position on the hexagol border and plus Ddisance, then the second position is outside of hexagon (I mean that I want to generate random pair position inside of hexagol). Could anybody help me in generating this kind of scenario and fix the problem? Thanks.
For example as
R = 500; % hexagol radius
N = 50; % number pair positions
d_min = 10; % minimum distance
d_max = 100; % maximum distance
D = (d_max - d_min).*rand(N,1) + d_min; % randomly distance
X = [0,0]; % hexagol center
j=0;
while j < N
j=j+1;
theta(j)=2*pi*rand(1,1);
u= rand()+ rand();
if u < 1
r(j) = R * u;
else
r(j) = R * (2 - u);
end
% to create the first position
x1(j)=r(j)*cos(theta(j)) + X(1,1); % first x positions
y1(j)=r(j)*sin(theta(j)) + X(1,2); % first y positions
end
% to create the second position
x2(j) = x1(j) + D(j); % second x positions
y2(j) = y1(j) + D(j); % second y positions
This is quite like your other question and its solution is almost the same, but it needs a little more math. Let’s focus on one pair of points. There still are two steps:
Step 1: Find a random point that is inside the hexagon, and has distance d from its border.
Step 2: Find another point that has distance d from first point.
Main problem is step 1. We can say that a points that has distance d form a hexagon with radius r, is actually inside a hexagon with radius r-d. Then we just need to find a random point that lays on a hexagon!
Polar Formula of Hexagons:
I want to solve this problem in polar space, so I have to formulate hexagons in this space. Remember circle formula in polar space:
The formula of a hexagon in polar space is pretty much like its circumscribe circle, except that the radius of the hexagon differs at every t (angle). Let’s call this changing radius r2. So, if we find the function R2 that returns r2 for all ts then we can write polar formula for hexagon:
This image demonstrates parameters of the problem:
The key parameter here is α. Now we need a function Alpha that returns α for all ts:
Now we have all points on border of the hexagon in polar space:
r = 500;
T = linspace(0, 2*pi, 181);
Alpha = #(t) pi/2-abs(rem(t, pi/3)-(pi/6));
R2 = #(t) r*cos(pi/6)./sin(Alpha(t));
X = R2(T).*cos(T);
Y = R2(T).*sin(T);
hold on
plot(X, Y, '.b');
plot((r).*cos(T), (r).*sin(T), '.r')
Polar Formula of a Regular Polygon:
Before I go on I’d like to generalize Alpha and R2 functions to cover all regular polygons:
Alpha = #(t) pi/2-abs(rem(t, 2*pi/(n))-(pi/(n)));
R2 = #(t) r*cos(pi/n)./sin(Alpha(t));
Where n is the number of edges of the polygon.
Answer:
Now we can generate pairs of points just like what we did for the circle problem:
r = 500; n = 6;
a = 10; b = 50;
N = 100;
D = (b - a).*rand(N,1) + a;
Alpha = #(t) pi/2-abs(rem(t, 2*pi/(n))-(pi/(n)));
R2 = #(t) r*cos(pi/n)./sin(Alpha(t));
T1 = rand(N, 1) * 2 * pi;
RT1 = rand(N, 1) .* (R2(T1)-D);
X1 = RT1.*cos(T1);
Y1 = RT1.*sin(T1);
T2 = rand(N, 1) * 2 * pi;
X2 = X1+D.*cos(T2);
Y2 = Y1+D.*sin(T2);
Rotating the polygon:
For rotating the polygon we just need to update the Alpha function:
t0 = pi/8;
Alpha = #(t) pi/2-abs(rem(t+t0, 2*pi/(n))-(pi/(n)));
This is a test for n=7, N=50000 and t0=pi/10:

Animating a ball in Matlab

I have a ball with these two equations:
x(t) = v0*cos(α)*t and
y(t) = h + v0*sin(α)*t− 1/2 gt^2 , where t ∈ [0,t final] is the time variable, h is the height, v0 is the initial speed, α is the angle made by v0 with the horizontal, g = 9.8 m/s^2. The floor is at y(x) = 0.
I need to draw a small animation of the ball moving on the plot. I now I should use for, plot, drawnow, but I don't know how to do it.
Can you tell me how to obain this animation?
First, here are some test variables to start with, including the acceleration due to gravity:
g = 9.8; %// m/s^2
v0 = 2; %// m/s
alpha = pi/6; %// Radians
h = 30; %// Start at 30 metres
t_final = 4.5; %// Seconds
t_vector = 0 : 0.01 : t_final;
t_vector in the last line of code creates a vector of points from the initial time of t = 0 up until our ending time in steps of 0.01. With these defined, our job is to go through each of these points in our vector and plot our ball. Next, let's create anonymous functions for each x and y to make our plotting easier:
x = #(t) v0*cos(alpha)*t;
y = #(t) h + v0*sin(alpha)*t - 0.5*g*t.^2;
What you can do next is use a for loop and go through each value of t_vector up until t_final and plot the individual point. You should probably make the point big so we can actually see what the ball looks like:
close all;
figure; hold on;
for t = t_vector
plot(x(t), y(t), 'b.', 'MarkerSize', 16);
axis([0 t_final 0 h]);
pause(0.01);
end
The above code will first close any figures we have open, spawn a new figure and use hold on so that we can call plot multiple times and append points to the graph without it erasing each time. Then, for each point in time, we plot the location on the graph as a blue dot, then make the size of the dot 16. We also make sure that the axis doesn't automatically adjust itself by enforcing that the x values are restricted between t = 0 up to t = t_final. We also restrict the y values from y = 0 up to the initial starting height, which is 30 in my example. At each point, we pause by 0.01 ms so you can see the drawing of the points.
As a bonus, this is what the figure looks like as an animated gif:

Homographic image transformation distortion issue

I am trying to transform an image using a 3D transformation matrix and assuming my camera is orthonormal.
I am defining my homography using the plane-induced homography formula H=R-t*n'/d (with d=Inf so H=R) as given in Hartley and Zisserman Chapter 13.
What I am confused about is when I use a rather modest rotation, the image seems to be distorting much more than I expect (I'm sure I'm not confounding radians and degrees).
What could be going wrong here?
I've attached my code and example output.
n = [0;0;-1];
d = Inf;
im = imread('cameraman.tif');
rotations = [0 0.01 0.1 1 10];
for ind = 1:length(rotations)
theta = rotations(ind)*pi/180;
R = [ 1 0 0 ;
0 cos(theta) -sin(theta);
0 sin(theta) cos(theta)];
t = [0;0;0];
H = R-t*n'/d;
tform = maketform('projective',H');
imT = imtransform(im,tform);
subplot(1,5,ind) ;
imshow(imT)
title(['Rot=' num2str(rotations(ind)) 'deg']);
axis square
end
The formula H = R-t*n'/d has one assumption which is not met in your case:
This formula implies that you are using pinhole camera model with focal length=1
But in your case, for your camera to be more real and for your code to work, you should set the focal length to some positive number much greater than 1. (focal length is the distance from your camera center to the image plane)
To do this you can define a calibration matrix K which handles the focal length. You just need to change your formula to
H=K R inv(K) - 1/d K t n' inv(K)
in which K is a 3-by-3 identity matrix whose two first elements along the diagonal are set to the focal length (e.g. f=300). The formula can be easily derived if you assume a projective camera.
Below is the corrected version of your code, in which the angles make sense.
n = [0;0;-1];
d = Inf;
im = imread('cameraman.tif');
rotations = [0 0.01 0.1 30 60];
for ind = 1:length(rotations)
theta = rotations(ind)*pi/180;
R = [ 1 0 0 ;
0 cos(theta) -sin(theta);
0 sin(theta) cos(theta)];
t = [0;0;0];
K=[300 0 0;
0 300 0;
0 0 1];
H=K*R/K-1/d*K*t*n'/K;
tform = maketform('projective',H');
imT = imtransform(im,tform);
subplot(1,5,ind) ;
imshow(imT)
title(['Rot=' num2str(rotations(ind)) 'deg']);
axis square
end
You can see the result in the image below:
You can also rotate the image around its center. For it to happen you should set the image plane origin to the center of the image which I think is not possible with that method of matlab (maketform).
You can use the method below instead.
imT=imagehomog(im,H','c');
Note that if you use this method, you'll have to change some settings in n, d, t and R to get the appropriate result.
That method can be found at: https://github.com/covarep/covarep/blob/master/external/voicebox/imagehomog.m
The result of the program with imagehomog and some changes in n, d, t , and R is shown below which seems more real.
New settings are:
n = [0 0 1]';
d = 2;
t = [1 0 0]';
R = [cos(theta), 0, sin(theta);
0, 1, 0;
-sin(theta), 0, cos(theta)];
Hmm... I'm not 100% percent on this stuff, but it was an interesting question and relevant to my work, so I thought I'd play around and give it a shot.
EDIT: I tried this once using no built-ins. That was my original answer. Then I realized that you could do it your way pretty easily:
The easy answer to your question is to use the correct rotation matrix about the z-axis:
R = [cos(theta) -sin(theta) 0;
sin(theta) cos(theta) 0;
0 0 1];
Here's another way to do it (my original answer):
I'm going to share what I did; hopefully this is useful to you. I only did it in 2D (though that should be easy to expand to 3D). Note that if you want to rotate the image in plane, you will need to use a different rotation matrix that you have currently coded. You need to rotate about the Z-axis.
I did not use those matlab built-ins.
I referred to http://en.wikipedia.org/wiki/Rotation_matrix for some info.
im = double(imread('cameraman.tif')); % must be double for interpn
[x y] = ndgrid(1:size(im,1), 1:size(im,2));
rotation = 10;
theta = rotation*pi/180;
% calculate rotation matrix
R = [ cos(theta) -sin(theta);
sin(theta) cos(theta)]; % just 2D case
% calculate new positions of image indicies
tmp = R*[x(:)' ; y(:)']; % 2 by numel(im)
xi = reshape(tmp(1,:),size(x)); % new x-indicies
yi = reshape(tmp(2,:),size(y)); % new y-indicies
imrot = interpn(x,y,im,xi,yi); % interpolate from old->new indicies
imagesc(imrot);
My own question now is: "How do you change the origin about which you are rotating the image? Clearly, I'm rotating about (0,0), the top left corner.
EDIT 2 In response to the asker's comment, I've tried again.
This time I fixed a couple of things. Now I'm using the same transformation matrix (about x) as in the original question.
I rotated about the center of the image by redoing the way i do the ndgrids (put 0,0,0) in the center of the image. I also decided to show 3 planes of the image. This was not in the original question. The middle plane is the plane of interest. To get just the middle plane, you can leave out the zero-padding and redefine the 3rd ndgrid option to be just 1 instead of -1:1.
im = double(imread('cameraman.tif')); % must be double for interpn
im = padarray(im, [0 0 1],'both');
[x y z] = ndgrid(-floor(size(im,1)/2):floor(size(im,1)/2)-1, ...
-floor(size(im,2)/2):floor(size(im,2)/2)-1,...
-1:1);
rotation = 1;
theta = rotation*pi/180;
% calculate rotation matrix
R = [ 1 0 0 ;
0 cos(theta) -sin(theta);
0 sin(theta) cos(theta)];
% calculate new positions of image indicies
tmp = R*[x(:)'; y(:)'; z(:)']; % 2 by numel(im)
xi = reshape(tmp(1,:),size(x)); % new x-indicies
yi = reshape(tmp(2,:),size(y)); % new y-indicies
zi = reshape(tmp(3,:),size(z));
imrot = interpn(x,y,z,im,xi,yi,zi); % interpolate from old->new indicies
figure;
subplot(3,1,1);imagesc(imrot(:,:,1)); axis image; axis off;
subplot(3,1,2);imagesc(imrot(:,:,2)); axis image; axis off;
subplot(3,1,3);imagesc(imrot(:,:,3)); axis image; axis off;
You are performing rotations around the x-axis: in your matrix, the 1st component (x) is left unchanged by the rotation matrix. This is confirmed by the perspective deformations from your examples.
The actual amount of deformation will then depend on the distance between the camera and the image plane (or more accurately on its value relative to the focal length of the camera). It can be important when the cameraman image plane is located near the camera.