Convert 1x1 sym to float - matlab

I attempt to convert a 1x1 sym to float in the program below below but it fails. Why?
The culprit line:
sol = ode45(M,[30 45],[double(H0) double(V0)]);
The error message:
Error using odearguments (line 111) Inputs must be floats, namely
single or double.
Error in ode45 (line 114) [neq, tspan, ntspan, next, t0, tfinal, tdir,
y0, f0, odeArgs, odeFcn, ...
Error in extra_credit_HW5_ME70 (line 60) sol = ode45(M,[30
45],[subs(H0) subs(V0)]);
The code:
clc;
clear all;
close all;
%This program solves the rocket program by using a system of second order
%differential which I derived (see Homework 5)
%code explanation from http://www.mathworks.com/products/symbolic/code-examples.html? file=/products/demos/symbolictlbx/second_order_differential_equation/solve-a-second-order-differential-equation.html
Ve=3500;
Mo=400;
Me=5;
g=9.81;
Cd=.5;
Af=.2;
R=287
T=273.15;
Patm=101325;
syms y(t);
%Note: From the hw: "Take the density of air at sea level to be 1.21
%kg/m3." I decided to model the density with an exponential function p(h)=(Patm*exp(-g*y/(R*T))/(R*T))
V = odeToVectorField(diff(y, 2) == Ve*Me/(Mo-Me.*t)-g-.5*Cd* (Patm*exp(-g*y/(R*T))/(R*T)) *diff(y).^2*Af/(Mo-Me.*t));
M = matlabFunction(V,'vars', {'t','Y'});
sol = ode45(M,[0 30],[0 0]);
x = linspace(0,30,250);
y = deval(sol,x,1);
plot(x,y);
% legend('No air resistance, air resistance');
hold on;
Mo=350;
syms y(t);
%Initial conditions for case where mass is dumped.
H0=y(end);
V0=( (y(end)-y(end-1)) / (x(end)-x(end-1)) );
%Note: From the hw: "Take the density of air at sea level to be 1.21
%kg/m3." I decided to model the density with an exponential function p(h)=(Patm*exp(-g*y/(R*T))/(R*T))
V = odeToVectorField(diff(y, 2) == Ve*Me/(Mo-Me.*t)-g-.5*Cd* (Patm*exp(-g*y/(R*T))/(R*T)) *diff(y).^2*Af/(Mo-Me.*t));
M = matlabFunction(V,'vars', {'t','Y'});
sol = ode45(M,[30 45],[double(H0) double(V0)]);
x = linspace(30,45,500);
y = deval(sol,x,1);
plot(x,y,'cyan');
% legend('No air resistance, air resistance');
title('Rocket height versus time for stages launch')
xlabel('time (seconds)')
ylabel('height (meters)')

Related

Downloaded Non-local means filter does not work

Below is a downloaded (I have customized it a little bit) algorithm for the Non-local means filter:
function [cleared] = Non_Local_Means(I,f,t,h)
[m,n] = size(I);
% Making gaussian kernel
su=1; %standard deviation of gaussian kernel
sm=0; % sum of all kernel elements (for normalization)
ks= 2*f+1; % size of kernel (same as neighborhood window size)
% Initiating kernel
ker = zeros(ks,ks);
for x=1:ks
for y=1:ks
ab = x-f-1; %horizontal distance of pixel from center(f+1, f+1)
cd = y-f-1; % vertical distance of pixel from center (f+1, f+1)
ker(x,y) = 100*exp(((ab*ab)+(cd*cd))/(-2*(su*su)));
sm = sm + ker(x,y);
end
end
kernel = ker ./ f;
kernel = kernel / sm; % normalization
% Assign a clear output image
cleared = zeros(m,n);
I = padarray(I,[f,f],'symmetric');
% Now we'll calculate ouput for each pixel
for i=1:m
for j=1:n
im = i+f; % to compensate for shift due to padarray function
jn= j+f;
% neighborhood of concerned pixel (we called it similarity window)
W1 = I(im-f:im+f , jn-f:jn+f);
% BOundaries of similarity window for that pixel
rmin = max(im-t, f+1);
rmax = min(im+t, m+f);
smin = max(jn-t, f+1);
smax = min(jn+t, n+f);
% Calculate weighted average next
NL=0; % same as cleared (i,j) but for simplicity
Z =0; % sum of all s(i,j)
% Run loop through all the pixels in similarity window
for r=rmin:rmax
for s=smin:smax
% neighborhood of pixel 'j' being compared for similarity
W2 = I(r-f:r+f, s-f:s+f);
% square of weighted euclidian distances
d2 = sum(sum(kernel.*(W1-W2).*(W1-W2))); %LINE 67
% weight of similarity between both pixels : s(i,j)
sij = exp(-d2/(h*h));
% update Z and NL
Z = Z + sij;
NL = NL + (sij*I(r,s));
end
end
% normalization of NL
cleared(i,j) = NL/Z;
end
end
% convert cleared to uint8
cleared = uint8(cleared);
end
But it gives me a subsequent mistake:
Error using .*
Integers can only be combined with integers of the same class, or scalar doubles.
Error in Non_Local_Means (line 67)
d2 = sum(sum(kernel.(W1-W2).(W1-W2)));
Error in filter_process (line 32)
eval(['filter_Images.',name_of_cells{i},'(',num2str(m),')','.',column_name{n},'(:,:,',num2str(p),')=Non_Local_Means(filter_Images.',name_of_cells{i},'(',num2str(m),')','.',column_name{n},'(:,:,',num2str(p),'),f,t,h);'])
Error in untitled>pushbutton13_Callback (line 1157)
handles.filtered_Images = filter_process(Images, f, t, h);
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in untitled (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in #(hObject,eventdata)untitled('pushbutton13_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl Callback
How can I solve this problem (LINE 67)?
Thank you in advance!

Problems using ode23 and function arguments in Matlab for differential equations

I am having problems with the following code. Next is shortened, but it tries to represent a chain of four pendulums.
% Simulation of double pendulum by Lagrangian mechanics
% see also http://www.eng.auburn.edu/~marghitu/MECH6710/06_Fall/MATLAB/C6_analytical/C6_MATLAB.pdf
close all
% generalized coordinates==================================================
syms t real
theta=sym('theta(t)');
phi=sym('phi(t)');
alpha=sym('alpha(t)'); %tercer angulo
gamma=sym('gamma(t)'); %cuarto ángulo
betha=sym('betha(t)'); %quinto ángulo
% constants, length, mass, g===============================================
L1=7; %lengths of all the pendulums
L2=6;
L3=6;
L4=6;
L5=6;
m1=3; %mass of all the particles
m2=3;
m3=3;
m4=3;
m5=3;
g=9.81;
i=0;
% positions and velocities as function of the generalized coordinates======
x1=L1*sin(theta);
y1=-i-L1*cos(theta);
x2=x1+L2*sin(phi);
y2=y1-L2*cos(phi);
x3=x2+L3*sin(alpha);
y3=y2-L3*cos(alpha);
x4=x3+L4*sin(gamma);
y4=y3-L4*cos(gamma);
x5=x4+L5*cos(betha);
y5=y4-L5*sin(betha);
x1dot=diff(x1,t);
x2dot=diff(x2,t);
x3dot=diff(x3,t);
x4dot=diff(x4,t);
x5dot=diff(x5,t);
y1dot=diff(y1,t);
y2dot=diff(y2,t);
y3dot=diff(y3,t);
y4dot=diff(y4,t);
y5dot=diff(y5,t);
% kinetic and potential energy=============================================
T=m1/2*(x1dot^2+y1dot^2)+m2/2*(x2dot^2+y2dot^2)+m3/2*(x3dot^2+y3dot^2)+m4/2*(x4dot^2+y4dot^2)+m5/2*(x5dot^2+y5dot^2);
V=m1*g*y1+m2*g*y2+m3*g*y3+m4*g*y4+m5*g*y5;
% Lagrangian ==============================================================
L=T-V;
% dL/d(qdot)===============================================================
dummy=sym('dummy');
dLthetadot = subs(diff(subs(L,diff(theta,t),dummy),dummy),dummy,diff(theta,t));
dLphidot = subs(diff(subs(L,diff(phi,t),dummy),dummy),dummy,diff(phi,t));
dLalphadot= subs(diff(subs(L,diff(alpha,t),dummy),dummy),dummy,diff(alpha,t));
dLgammadot=subs(diff(subs(L,diff(gamma,t),dummy),dummy),dummy,diff(gamma,t));
dLbetadot=subs(diff(subs(L,diff(betha,t),dummy),dummy),dummy,diff(betha,t));
% dL/dq====================================================================
dLdtheta=subs(diff(subs(L,theta,dummy),dummy),dummy,theta);
dLdphi=subs(diff(subs(L,phi,dummy),dummy),dummy,phi);
dLdalpha=subs(diff(subs(L,alpha,dummy),dummy),dummy,alpha);
dLdgamma=subs(diff(subs(L,gamma,dummy),dummy),dummy,gamma);
dLdbeta=subs(diff(subs(L,betha,dummy),dummy),dummy,betha);
% dFdq=====================================================================
k=0.5; % dissipation constant
F=1/2*k*(x1dot^2+y1dot^2+x2dot^2+y2dot^2+x3dot^2+y3dot^2+x4dot^2+y4dot^2+x5dot^2+y5dot^2);
dFdthetadot=subs(diff(subs(F,diff(theta,t),dummy),dummy),dummy,diff(theta,t));
dFdphidot=subs(diff(subs(F,diff(phi,t),dummy),dummy),dummy,diff(phi,t));
dFdalphadot=subs(diff(subs(F,diff(alpha,t),dummy),dummy),dummy,diff(alpha,t));
dFdgammadot=subs(diff(subs(F,diff(gamma,t),dummy),dummy),dummy,diff(gamma,t));
dFdbetadot=subs(diff(subs(F,diff(betha,t),dummy),dummy),dummy,diff(betha,t));
% generalized equations of motion==========================================
differentialequation1=diff(dLthetadot,t)-dLdtheta+dFdthetadot;
differentialequation2=diff(dLphidot,t)-dLdphi+dFdphidot;
differentialequation3=diff(dLalphadot,t)-dLdalpha+dFdalphadot;
differentialequation4=diff(dLgammadot,t)-dLdgamma+dFdgammadot;
differentialequation5=diff(dLbetadot,t)-dLdbeta+dFdbetadot;
% abbreviation of variables================================================
variables={theta,phi,alpha,gamma,betha,diff(theta,t),diff(phi,t),diff(alpha,t),diff(gamma,t),diff(betha,t),diff(theta,t,2),diff(phi,t,2),diff(alpha,t,2),diff(gamma,t,2),diff(betha,t,2)};
variablesshort={'x(1)','x(2)','x(3)','x(4)','x(5)','x(6)','x(7)','x(8)','x(9)','x(10)','thetaddot','phiddot','alphaddot','gammaddot','betaddot'};
DifferentialEquation1=subs(differentialequation1,variables,variablesshort);
DifferentialEquation2=subs(differentialequation2,variables,variablesshort);
DifferentialEquation3=subs(differentialequation3,variables,variablesshort);
DifferentialEquation4=subs(differentialequation4,variables,variablesshort);
DifferentialEquation5=subs(differentialequation5,variables,variablesshort);
% solve for thetaddot, phiddot=============================================
solution=solve(DifferentialEquation1,DifferentialEquation2,DifferentialEquation3,DifferentialEquation4,DifferentialEquation5,'thetaddot','phiddot','alphaddot','gammaddot','betaddot');
THETADDOT=solution.thetaddot;
PHIDDOT=solution.phiddot;
ALPHADDOT=solution.alphaddot;
GAMMADDOT=solution.gammaddot;
BETADDOT=solution.betaddot;
% solve non linear ode system==============================================
time=linspace(0,30,2000);
% initial conditions [theta,phi,thetadot,phidot]===========================
x0=[pi/4 0 0 0 0 0.5 0 0 0 0];
str=['xdot=#(t,x)[;x(6);x(7);x(8);x(9);x(10);',char(THETADDOT),';',char(PHIDDOT),';',char(ALPHADDOT),';',char(GAMMADDOT),';',char(BETADDOT),'];'];
eval(str);
[t,q]=ode23(xdot,time,x0);
% Calculute positions as function of generalized coordinates===============
X1=L1*sin(q(:,1));
Y1=-L1*cos(q(:,1));
X2=X1+L2*sin(q(:,2));
Y2=Y1-L2*cos(q(:,2));
X3=X2+L3*sin(q(:,3));
Y3=Y2-L3*cos(q(:,3));
X4=X3+L4*sin(q(:,4));
Y4=Y3-L4*cos(q(:,4));
X5=X4+L5*sin(q(:,5));
Y5=Y4-L5*cos(q(:,5));
% plot solution============================================================
set(gcf,'color',[1 1 1])
hold on
box on
axis equal
for i=1:numel(time)
cla;
plot([0,X1(i)],[0,Y1(i)],'k','linewidth',4);
plot(X1(i),Y1(i),'o','MarkerFaceColor','k','MarkerEdgeColor','k','MarkerSize',4*m1);
plot([X1(i),X2(i)],[Y1(i),Y2(i)],'k','linewidth',4);
plot(X2(i),Y2(i),'o','MarkerFaceColor','k','MarkerEdgeColor','k','MarkerSize',4*m2);
plot([X2(i),X3(i)],[Y2(i),Y3(i)],'k','linewidth',4);
plot(X3(i),Y3(i),'o','MarkerFaceColor','k','MarkerEdgeColor','k','MarkerSize',4*m3);
plot([X3(i),X4(i)],[Y3(i),Y4(i)],'k','linewidth',4);
plot(X4(i),Y4(i),'o','MarkerFaceColor','k','MarkerEdgeColor','k','MarkerSize',4*m4);
plot([X4(i),X5(i)],[Y4(i),Y5(i)],'k','linewidth',4);
plot(X5(i),Y5(i),'o','MarkerFaceColor','k','MarkerEdgeColor','k','MarkerSize',4*m5);
% plot(X2(1:i),Y2(1:i),'g-'); %aqui pinta la trayectoria de la bola 2
axis([-8,8,-1.05*(L1+L2+L3+L4+L5),0]);
drawnow
end
The error I see is next:
Undefined function or variable 'matrix'. Error in QuadruplePendulum2D>#(t,x)[x(5);x(6);x(7);x(8);matrix(0,1,[]);matrix(0,1,[]);matrix(0,1,[]);matrix(0,1,[])]
Error in odearguments (line 87) f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0
Error in odearguments (line 87) f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode23 (line 114) odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in QuadruplePendulum2D (line 86) [t,q]=ode23(xdot,time,x0);
Can anyone help in this error, please? Thanks

Too Many Input Arguments Matlab ode45

I am trying to write a simple Matlab code to model a projectile. Whenever I try to run the code I get an error saying there are too many input arguments. I am running the code with
model1(44.7, 45)
function[] = model1(vel, angle)
close all;
tspan = [0 3];
x0 = [0; 0.915; vel*cos(angle); vel*sin(angle)];
[x] = ode45(#ball, tspan, x0);
function xdot = ball(x)
g = 9.81;
xdot = [x(3); x(4); 0; -g];
end
end
Error using model1/ball
Too many input arguments.
Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options,
varargin);
Error in model1 (line 9)
[x] = ode45(#ball, tspan, x0);
I'd appreciate any advice!
The error was (what I also committed many times in the past) that you have to pass the independent variable (time, in this case) too.
function [t, x] = model1(vel, angle)
tspan = [0 3];
x0 = [0; 0.915; vel*cos(angle); vel*sin(angle)];
[t, x] = ode45(#ball, tspan, x0);
end
function xdot = ball(t,x)
g = 9.81;
xdot = [x(3); x(4); 0; -g];
end
I modified your code to return the solution and the corresponding time steps. Moreover, I removed ball to be a nested function.

MATLAB - How to read a single value from a vector? (ode45 involved)

I'm trying to work with a code that involves ode45, in the one in the equation that will be solved I have to introduce a single value from a vector that will change depending on the time the equation is solved, I mean if it is x=x(0) then u1(1) and u2(t), when x=x(1) then u1(2), u2(2)... This is my code:
function [sal] = scobe1
clear
clc
global a;
a=1;
assignin('base','a',a)
tspan = [0; 180];
x0 = [80; 0];
[t,x] = ode45(#f,tspan,x0);
sal=[t,x]
figure
subplot(2,1,1)
plot(t,x(:,1),'k-');
subplot(2,1,2)
plot(t,x(:,2),'b-');
function dxdt = f(t,x)
global a s1 u1 u2 newData;
newData=importdata('datosnoembarazo.mat');
assignin('base','newData',newData);
u1=getfield(newData,'glucosa4dias');
assignin('base','u1',u1);
u2=getfield(newData,'insulina4dias');
assignin('base','u2',u2);
u1=getfield(newData,'glucosa4dias');
assignin('base','u1',u1);
u2=getfield(newData,'insulina4dias');
assignin('base','u2',u2);
if (a<=s1)
dxdt = [
(-4.9e-2-x(2))*x(1) + (4.42 + u1(a)) %(1) IN HERE u1 IS THE VECTOR'S NAME
-9.1e-2*x(2) + u2(a) %(2) IN HERE u2 IS THE VECTOR'S NAME
];
a=a+1
assignin('base','a',a);
else return
end
The problem is that it sends me this error: And I don't know what is wrong with the code, or what else can I do in order for it to read it, can you please help me? Thanks
Error in scobe1>f (line 36)
global a s1 s2 u1 u2 newData;
Error using feval
Output argument "dxdt" (and maybe others) not assigned during call to
"C:\Users\AnnieA\Dropbox\Tesis (A. Olay)\GUI Examples\Resumen de Modelos\scobe1.m>f".
Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 113)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ...
Error in scobe1 (line 25)
[t,x] = ode45(#f,tspan,x0);
Your function function dxdt = f(t,x) has two branches in the if statement: If a<=s1, then dxdt gets assigned correctly. If a>s1, dxdt is not assigned at all. You can fix the error by assigning a value to dxdt in the else branch of your if statment before you return. I am not sure what an appropriate value would be in this case. Perhaps 0?

Second Order Diff Eq with ode45 in Matlab

So I need to solve x''(t) = -x(t)^p with initial conditions x(0)= 0 and v(0) = x'(0) = v_o = 1.
The value of the parameter p is 1.
This is what I have:
function [t, velocity, x] = ode_oscilation(p)
y=[0;0;0];
% transform system to the canonical form
function y = oscilation_equation(x,p)
y=zeros(2,1);
y(1)=y(2);
y(2)=-(x)^p;
% to make matlab happy we need to return a column vector
% so we transpose (note the dot in .')
y=y.';
end
tspan=[0, 30]; % time interval of interest
[t,velocity,x] = ode45(#oscilation_equation, tspan, 1);
t = y(:,1);
xposition=y(:,3);
velocity=y(:,2);
end
and this is the error message I receive:
ode_oscillation(1)
Error using odearguments (line 91)
ODE_OSCILLATION/OSCILATION_EQUATION must return a
column vector.
Error in ode45 (line 114)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0,
odeArgs, odeFcn, ...
Error in ode_oscillation (line 17)
[t,velocity,x] = ode45(#oscilation_equation, tspan,1);
There's a few things going wrong here. First, from help ode45:
ode45 Solve non-stiff differential equations, medium order method.
[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates
the system of differential equations y' = f(t,y) from time T0 to TFINAL
with initial conditions Y0.
Note that ode45 expects a function f(t,y), where size(t) == [1 1] for time and size(y) == [1 N] or [N 1] for solution values. Your oscilation_equation has the order of input arguments inverted, and you input a constant parameter p instead of time t.
Also, the initial conditions Y0 should have the same size as y; so size(y0) == [N 1] or [1 N]. You just have 1, which is clearly causing errors.
Also, your output arguments t, xposition and velocity will be completely ignored and erroneous, since y is not set as output argument from ode45, and most of all, their names do not correspond to ode_oscilation's output arguments. Also, their order of extracting from columns of y is incorrect.
So, in summary, change everything to this:
function [t, v, x] = ode_oscilation(p)
% initial values
y0 = [0 1];
% time interval of interest
tspan =[0 30];
% solve system
[t,y] = ode45(#(t,y) [y(2); -y(1)^p], tspan, y0);
% and return values of interest
x = y(:,1);
v = y(:,2);
end