Plotting animation results in blank graph - matlab

I have written this code and it will not plot. I run it with a 0:.5:100 and get a blank graph in Matlab. As well this is a inclined plane friction problem. I need to create an animation in Matlab that shows the blocks sliding based on inputs.
%Numerical Project Code 1
%mass ratio input
mratio = input('Enter the Mass Ratio(m/M): ');
%angle input
theta = input('Enter Angle in Degrees Between 0 and 90: ');
%static coeff input
mus = input('Enter Coefficient of Static Friction: ');
%kinetic coeff input
muk = input('Enter Coefficient of Kinetic Friction: ');
%constants
g = 9.81;
%interface formating
disp('--------------------------------------------');
disp('All Friction Forces are given in terms of the mass on the slope (M)');
%Loops
%NETUP
if mratio > sind(theta)
%static only
if mratio <= (sind(theta) + (mus*cosd(theta)))
ff = g*(mratio - sind(theta));
fprintf("Friction Force = %f M Newtons\n",ff);
fprintf("The Direction of the Friction Force is down the slope and the block not moving.\n")
%kinetic only
else
ff = muk * g * cosd(theta);
fprintf("Friction Force = %f M Newtons\n",ff);
fprintf("The Direction of the Friction Force is down the slope and the block is sliding up the slope.\n");
end
%NETDOWN
elseif mratio < sind(theta)
%static only
if sind(theta) <= (mratio + (mus*cosd(theta)))
ff = g*(sind(theta) - mratio);
fprintf("Friciton Force = %f M Newtons\n",ff);
fprintf("The Direction of the Friction Force is up the slope and the block is not moving.\n")
%kinetic only
else
ff = muk * g * cosd(theta);
fprintf("Friction Force = %f M Newtons\n",ff);
fprintf("The Direction of the Friction Force is up the slope and the block is sliding down the slope.\n");
end
%NETZERO
else
fprintf("Friction Force = 0 Newtons\n");
end
%graph
for i = 0:0.01:1
mratiog = i;
if mratiog > sind(theta)
if mratiog <= (sind(theta) + (mus*cosd(theta)))
ffg = g*(mratiog - sind(theta));
else
ffg = muk * g * cosd(theta);
end
elseif mratiog < sind(theta)
if sind(theta) <= (mratiog + (mus*cosd(theta)))
ffg = g*(sind(theta) - mratiog);
else
ffg = muk * g * cosd(theta);
end
else
ffg = 0;
end
plot (ffg,mratio, 'r:')
end

In addition to Erik's comments I see two other issues:
the plot changes its axis with each new iteration, so you can not see
the animation properly. It would work better if you calculate all
your points before plotting them. Then you can use min and max of data
dimensions to set axis limits. If you don't use 'hold on' you need to set the limits in each iteration.
you need to use 'pause' to slow down the
animation. otherwise you see only the last data point.
Here is a working example of the 'graph' part:
%graph
i_arr = 0:0.01:1;
n = numel(i_arr);
ffg_mratio_arr = zeros(n, 2);
for i = 1:n
mratiog = i_arr(i);
if mratiog > sind(theta)
if mratiog <= (sind(theta) + (mus*cosd(theta)))
ffg = g*(mratiog - sind(theta));
else
ffg = muk * g * cosd(theta);
end
elseif mratiog < sind(theta)
if sind(theta) <= (mratiog + (mus*cosd(theta)))
ffg = g*(sind(theta) - mratiog);
else
ffg = muk * g * cosd(theta);
end
else
ffg = 0;
end
ffg_mratio_arr(i,:) = [ffg mratio];
end
% calculating the axis limits
x_min = min(ffg_mratio_arr(:, 1))-1;
x_max = max(ffg_mratio_arr(:, 1))+1;
y_min = min(ffg_mratio_arr(:, 2))-1;
y_max = max(ffg_mratio_arr(:, 2))+1;
% animation
figure;
for i = 1:n
plot (ffg_mratio_arr(i,1), ffg_mratio_arr(i,2), 'ro');
xlim([x_min x_max]);
ylim([y_min y_max]);
pause(0.01);
end

Related

matlab generalized cross correlation and ROTH Filter

I have a problem for finding cross correlation of tho signals. No filtere version works but ROTH filter version does not work. Can you tell me the problem please ? Thanks
tho=2;
A=1;
t=-15:0.1:15;
FFTLength=length(t);
x= rect( t+1,tho,A ); % First rectangle signal
plot(t,x)
hold on
y=rect(t-4,tho,A);
plot(t,y,'r')
for i=1:length(x)
x(i)=x(i)+normrnd(0,0.1);
end
figure
plot(t,x,'r')
for i=1:length(y)
y(i)=y(i)+normrnd(0,0.1);
end
figure
plot(t,y,'r')
Rxx = xcorr(x);
Ryy = xcorr(y);
Rxy = xcorr(x,y);
Sxx = fft(Rxx,FFTLength);
Syy = fft(Ryy,FFTLength);
Sxy = fft(Rxy,FFTLength);
X=fft(x,301);
Y=fft(y,301);
%Filtering
H=1;
X2=X.*H;
Y2=Y.*H;
x_t=ifft(X2);
y_t=ifft(Y2);
[correlation,lags] = xcorr(y_t,x_t);
delay = lags(find(correlation==max(correlation)))
disp('Plain time ')
X2=fft(x).*(1./Sxx);
Y2=fft(Y).*(1./Sxx);
x2=real(ifft(X2));
y2=real(ifft(Y2));
[correlation2,lags2] = xcorr(x2,y2);
delay2 = lags2(find(correlation2==max(correlation2)))
disp('ROTH Filter ');
by the way rect is ;
function [ y ] = rect( t,tho,A )
for i = 1 : length(t)
if -(tho / 2) <= t(i) && t(i) <= (tho / 2)
y(i) = A * 1;
else
y(i) = 0;
end
end
end

`ode45` and tspan error Attempted to access

I'm using ode45 to solve second order differential equation. the time span is determined based on how many numbers in txt file, therefore, the time span is defined as follows
i = 1;
t(i) = 0;
dt = 0.1;
numel(theta_d)
while ( i < numel(theta_d) )
i = i + 1;
t(i) = t(i-1) + dt;
end
Now the time elements should not exceed the size of txt (i.e. numel(theta_d)). In main.m, I have
x0 = [0; 0];
options= odeset('Reltol',dt,'Stats','on');
[t, x] = ode45('ODESolver', t, x0, options);
and ODESolver.m header is
function dx = ODESolver(t, x)
If I run the code, I'm getting this error
Attempted to access theta_d(56); index out of bounds because numel(theta_d)=55.
Error in ODESolver (line 29)
theta_dDot = ( theta_d(i) - theta_dPrev ) / dt;
Why the ode45 is not being fixed with the time span?
Edit: this is the entire code
main.m
clear all
clc
global error theta_d dt;
error = 0;
theta_d = load('trajectory.txt');
i = 1;
t(i) = 0;
dt = 0.1;
numel(theta_d)
while ( i < numel(theta_d) )
i = i + 1;
t(i) = t(i-1) + dt;
end
x0 = [pi/4; 0];
options= odeset('Reltol',dt,'Stats','on');
[t, x] = ode45(#ODESolver, t, x0, options);
%e = x(:,1) - theta_d; % Error theta
plot(t, x(:,2), 'r', 'LineWidth', 2);
title('Tracking Problem','Interpreter','LaTex');
xlabel('time (sec)');
ylabel('$\dot{\theta}(t)$', 'Interpreter','LaTex');
grid on
and ODESolver.m
function dx = ODESolver(t, x)
persistent i theta_dPrev
if isempty(i)
i = 1;
theta_dPrev = 0;
end
global error theta_d dt ;
dx = zeros(2,1);
%Parameters:
m = 0.5; % mass (Kg)
d = 0.0023e-6; % viscous friction coefficient
L = 1; % arm length (m)
I = 1/3*m*L^2; % inertia seen at the rotation axis. (Kg.m^2)
g = 9.81; % acceleration due to gravity m/s^2
% PID tuning
Kp = 5;
Kd = 1.9;
Ki = 0.02;
% theta_d first derivative
theta_dDot = ( theta_d(i) - theta_dPrev ) / dt;
theta_dPrev = theta_d(i);
% u: joint torque
u = Kp*(theta_d(i) - x(1)) + Kd*( theta_dDot - x(2)) + Ki*error;
error = error + (theta_dDot - x(1));
dx(1) = x(2);
dx(2) = 1/I*(u - d*x(2) - m*g*L*sin(x(1)));
i = i + 1;
end
and this is the error
Attempted to access theta_d(56); index out of bounds because numel(theta_d)=55.
Error in ODESolver (line 28)
theta_dDot = ( theta_d(i) - theta_dPrev ) / dt;
Error in ode45 (line 261)
f(:,2) = feval(odeFcn,t+hA(1),y+f*hB(:,1),odeArgs{:});
Error in main (line 21)
[t, x] = ode45(#ODESolver, t, x0, options);
The problem here is because you have data at discrete time points, but ode45 needs to be able to calculate the derivative at any time point in your time range. Once it solves the problem, it will interpolate the results back onto your desired time points. So it will calculate the derivative many times more than at just the time points you specified, thus your i counter will not work at all.
Since you have discrete data, the only way to proceed with ode45 is to interpolate theta_d to any time t. You have a list of values theta_d corresponding to times 0:dt:(dt*(numel(theta_d)-1)), so to interpolate to a particular time t, use interp1(0:dt:(dt*(numel(theta_d)-1)),theta_d,t), and I turned this into an anonymous function to give the interpolated value of theta_p at a given time t
Then your derivative function will look like
function dx = ODESolver(t, x,thetaI)
dx = zeros(2,1);
%Parameters:
m = 0.5; % mass (Kg)
d = 0.0023e-6; % viscous friction coefficient
L = 1; % arm length (m)
I = 1/3*m*L^2; % inertia seen at the rotation axis. (Kg.m^2)
g = 9.81; % acceleration due to gravity m/s^2
% PID tuning
Kp = 5;
Kd = 1.9;
Ki = 0.02;
% theta_d first derivative
dt=1e-4;
theta_dDot = (thetaI(t) - theta(I-dt)) / dt;
%// Note thetaI(t) is the interpolated theta_d values at time t
% u: joint torque
u = Kp*(thetaI(t) - x(1)) + Kd*( theta_dDot - x(2)) + Ki*error;
error = error + (theta_dDot - x(1));
dx=[x(2); 1/I*(u - d*x(2) - m*g*L*sin(x(1)))];
end
and you will have to define thetaI=#(t) interp1(0:dt:(dt*(numel(theta_d)-1)),theta_d,t); before calling ode45 using [t, x] = ode45(#(t,x) ODESolver(t,x,thetaI, t, x0, options);.
I removed a few things from ODESolver and changed how the derivative was computed.
Note I can't test this, but it should get you on the way.

Undefined variable in 'if' statement

I'm writing a script for an aerodynamics class and I'm getting the following error:
Undefined function or variable 'dCt_dx'.
Error in Project2_Iteration (line 81)
Ct = trapz(x,dCt_dx)
I'm not sure what the cause is. It's something to do with my if statement. My script is below:
clear all
clc
global dr a n Vinf Vr w rho k x c cl dr B R beta t
%Environmental Parameters
n = 2400; %rpm
Vinf = 154; %KTAS
rho = 0.07647 * (.7429/.9450); %from mattingly for 8kft
a = 1084; %speed of sound, ft/s, 8000 ft
n = n/60; %convert to rps
w = 2*pi*n;
Vinf = (Vinf*6076.12)/3600; %convert from KTAS to ft/s
k = length(c);
dr = R/k; %length of each blade element
for i = 1:k
r(i) = i*dr - (.5*dr); %radius at center of blade element
dA = 2*pi*r*dr; %Planform area of blade element
x(i) = r(i)/R;
if x(i) > .15 && x(i-1) < .15
i_15 = i;
end
if x(i) > .75 && x(i-1) < .75
i_75h = i;
i_75l = i-1;
end
Vr(i) = w*r(i) + Vinf;
%Aerodynamic Parameters
M = Vr(i)/a;
if M > 0.9
M = 0.9;
end
m0 = 0.9*(2*pi/(1-M^2)^0.5); %lift-curve slope (2pi/rad)
%1: Calculate phi
phi = atan(Vinf/(2*pi*n*r(i)));
%2: Choose Vo
Vo = .00175*Vinf;
%3: Calculate Theta
theta = atan((Vinf + Vo)/(2*pi*n*r(i)))-phi;
%4:
if option == 1
%calculate cl(i) from c(i)
sigma = (B*c(i))/(pi*R);
if sigma > 0
cl(i) = (8*x(i)*theta*cos(phi)*tan(phi+theta))/sigma;
else
cl(i) = 0;
end
else %option == 2
%calculate c(i) from cl(i)
if cl(i) ~= 0
sigma = (8*x(i)*theta*cos(phi)*tan(phi+theta))/cl(i);
else
sigma = 0;
end
c(i) = (sigma*pi*R)/B;
if c(i) < 0
c(i) = 0;
end
end
%5: Calculate cd
cd(i) = 0.0090 + 0.0055*(cl(i)-0.1)^2;
%6: calculate alpha
alpha = cl(i)/m0;
%7: calculate beta
beta(i) = phi + alpha + theta;
%8: calculate dCt/dx and dCq/dx
phi0 = phi+theta;
lambda_t = (1/(cos(phi)^2))*(cl(i)*cos(phi0) - cd(i)*sin(phi0));
lambda_q = (1/(cos(phi)^2))*(cl(i)*sin(phi0) + cd(i)*cos(phi0));
if x(i) >= 0.15
dCt_dx(i) = ((pi^3)*(x(i)^2)*sigma*lambda_t)/8; %Roskam eq. 7.47, pg. 280
dCq_dx(i) = ((pi^3)*(x(i)^3)*sigma*lambda_q)/16; %Roskam eq. 7.48, pg 280
else
dCt_dx(i) = 0;
dCq_dx(i) = 0;
end
%calculate Mdd
t(i) = (0.04/(x(i)^1.2))*c(i);
Mdd(i) = 0.94 - (t(i)/c(i)) - cl(i)/10;
end
%9: calculate Ct, Cq, Cd
Ct = trapz(x,dCt_dx)
Cq = trapz(x,dCq_dx)
D = 2*R;
Q=(rho*(n^2)*(D^5)*Cq)
T=(rho*(n^2)*(D^4)*Ct)
When I step through your script, I see that the the entire for i = 1:k loop is skipped because k=0. You set k = length(c), but c was never initialized to a value, so it has length zero.
Because of this, dCt_dx is never given a value--and more importantly the majority of your script is never run.
If you're going to be using MATLAB in the future, I really suggest learning how to do this. It makes it a lot easier to find bugs. Try looking at this video.

line equation for lane lines

i have to find the mid points of each lane in a binary iamge , i wrote a code but that is too long and its give error when ever i change the pic of road . i have to save the mid points of each lane and then by finding slope and intercept i have to draw lines on that binary image.
here is the code
x=imread('C:\users\guest\documents\matlab\1.png');
[q,r]= size(x);
n4=zeros(q,r);
midpoint= zeros (720,2); % Array to store midlle points of road lane.
% finding mid points of both lanes.
for n3=540:720
s=x(n3,:);
startIndex =1;
lastIndex =1280;
pixelsRow =s;
FirstWhiteStart=0; FirstWhiteEnd=0; SecondWhiteStart=0; SecondWhiteEnd=0;
for k=1:1280
if (pixelsRow(k) == 1)&&(FirstWhiteStart == 0)
FirstWhiteStart =k;
elseif (pixelsRow(k)==0)&&(FirstWhiteStart>0)&&(FirstWhiteEnd==0)
FirstWhiteEnd=k-1;
elseif (pixelsRow(k)== 1)&&(FirstWhiteEnd>0)&&(SecondWhiteStart==0)
SecondWhiteStart=k;
elseif (pixelsRow(k)==0)&&(SecondWhiteStart>0)&&(SecondWhiteEnd==0)
SecondWhiteEnd=k-1;
end
end
m1=(FirstWhiteStart + FirstWhiteEnd)./2; % first lanes middle point
m1r = round(m1);
if (m1r <= 1)
mp= sub2ind(size(midpoint),n3,1);
midpoint(mp) = 0;
elseif (m1r > 1)
indices = sub2ind(size(n4),n3,m1r);
n4(indices) = 1;
if (m1r >=640)
mp= sub2ind(size(midpoint),n3,2);
midpoint(mp) = m1r;
elseif (m1r <= 640)
mp= sub2ind(size(midpoint),n3,1);
midpoint(mp) = m1r;
end
end
m2=(SecondWhiteStart + SecondWhiteEnd+1)./2; % second lane middle point.
m2r = round(m2);
if (m2r <= 1)
indices = sub2ind(size(n4),n3,m2r);
n4(indices) = 0;
mp= sub2ind(size(midpoint),n3,1);
midpoint(mp) = 0;
elseif (m2r > 1)
indices = sub2ind(size(n4),n3,m2r);
n4(indices) = 1;
if (m2r >=640)
mp= sub2ind(size(midpoint),n3,2);
midpoint(mp) = m2r;
elseif (m2r <=640)
mp= sub2ind(size(midpoint),n3,1);
midpoint(mp) = m2r;
end
end
end
pairpoints = nchoosek([540:720],2);
var1 = zeros (16290,2); % array to store variables a and b of first lane.
var2 = zeros (16290,2); % array to stote variables a and b of second lane.
% calling middle points previously stored in array,putting in equation.
for n = 1 : 16290
x1 = pairpoints(n,1); %value of frst row
x2 = pairpoints(n,2); %value of 2nd row
y1 = midpoint (pairpoints(n,1), 1); %rows of midpoint matrix are specified from pairpoints location martix
y2 = midpoint (pairpoints(n,2), 1);
z1 = midpoint (pairpoints(n,1), 2);
z2 = midpoint (pairpoints(n,2), 2);
a1 = (y2 - y1) ./ (x2 - x1);
a2 = (z2 - z1) ./ (x2 - x1);
b1=(((x2)*(y1)) - (x1)*(y2)) ./ (x2 - x1);
b2=(((x2)*(z1)) - (x1)*(z2)) ./ (x2 - x1);
% variables a and b of first lane.
line = sub2ind(size(var1),n,1);
var1(line) = a1;
line = sub2ind(size(var1),n,2);
var1(line) = b1;
% variables A and b of second lane.
line = sub2ind(size(var2),n,1);
var2(line) = a2;
line = sub2ind(size(var2),n,2);
var2(line) = b2;
end
v11=round(var1);
v22=round(var2);
% eleminating zeros from array.
[i,j] = find(v11);
a1 = v11(i,1);
a1= a1(a1~=0);
b1 = v11(i,2);
b1= b1(b1~=0);
a11=median(a1)
b11=median(b1)
% eleminating zeros from array.
[k,l] = find(v22);
row = i;
a2 = v22(k,1);
a2= a2(a2~=0);
b2 = v22(k,2);
b2= b2(b2~=0);
a22=median(a2)
b22=median(b2)
%assign variables
lin=zeros(720,2);
% implementation of final line equation.
for x1 = 1:720
% equation becomes (w = eh + f) as actual was (y = ax + b)
y1 = (a11 * x1) + b11;
y2 = (a22 * x1) + b22;
col = sub2ind( size(lin),x1,1); % equation for first lane.
lin(col)= y1;
col = sub2ind( size(lin),x1,2); % equation for second lane.
lin(col)= y2;
end
array=lin;
r= 1:720;
c= 1:1280;
x(r,c)= 0;
imshow(x);
imwrite(x,'a.png');
image =imread('C:\users\guest\documents\matlab\a.png');
for r1 = 1:720
for c = 1:2;
if array(r1,c) < 0;
lin(r1,c) = abs (array(r1,c));
image(r1,lin(r1,c))= 0;
elseif array(r1,c) > 0;
image(r1,lin(r1,c))= 1;
end
end
end
imshow(image)

Multiplying weight matrix of a trained neural network with a test vector

I trained the perceptron neural network and obtained the weight matrix using matlab.
The dimension of the obtained weight matrix is <50x1 double>
Now while giving the test input, I have a <1x1 double> value, that need's to be tested.
If I multiply the weight matrix with the value, I get <50x1 double>. How can I set threshold for <50x1 double> value.
Is there any way to get around this problem ?
This is the code
tic
clc; clear all; close all;
%function [ w1, bias ] = percep1( x )
zzz = xlsread('D:\matlab\NN_FILES\train_mean.xlsx')
s = zzz;
learning_rate = 0.1; % go with the loop mohan
theta = 10000;
w1=0;
for j = 1:50
x=s(:,j);t=1; bias=0; stopp=1; count=0;
while stopp
yin = bias + (w1*x);
% activation function
if yin > theta
y = 1;
elseif yin < -theta
y = -1;
else
y = 0;
end
if (t ~= y)
% for i = 1 : 7
%if ( x(i) ~= 0 )
w1 = w1 + ( learning_rate * t * x);
%end
% end
bias = bias + ( learning_rate * t);
end
count = count + 1;
if t==y
stopp = 0;
count;
end
end
w(j,:) = w1;
b1(j) = bias;
e1(j) = count;
end
new_weights_2 = w(50,:)
yyy= xlsread('D:\matlab\NN_FILES\test_mean.xlsx');
st=yyy;
theta2 = 1.0e+04 * 1.2 ;
for j=1:20
x=st(:,j);
yin=(new_weights_2(1))*(x)
output(j) = yin;
if yin > theta2
y = 1;
elseif yin < -theta2
y = -1;
else y = 0;
end
y1(j)=y;
end
toc
Now I have used only the first value of the weight matrix inorder to satisfy the multiplication rule. Is there any way to multiply the weight matrix with the test input ?