quaternion with symbolic variable - matlab

Is Matlab capable of handling quaternion with symbolic variables? There is no information in the documentation. The following script is not working
syms a
d=quaternion(1,2,3,a)
This is the actual error
All inputs to the quaternion constructor must be the same class (double or
single).

If the built-in quaternion objects supports sym types then try the array constructor
syms a
q = quaternion([1,2,3,a])
or
q = quaternion(str2sym('[1,2,3,a]'))
If MATLAB does not have an array constructor then you have do manually assign each value
v = str2sym('[1,2,3,a]');
q = quaternion(v(1),v(2),v(3),v(4))

Related

Time varying input ODE solving

I'm trying to solve a set of ODE equations using ode45. A number of my parameters are already a function of time but I keep getting errors.
function odo
dx(1,1) = (vl+vr)/2*cos(x(3));
dx(2,1) = (vl+vr)/2*sin(x(3));
dx(3,1) = obz
where obz, vr and vl are each vectors e.g:
obz = sin(t), t = 0:dt:tf;
I use the following syntax:
[t, x1] = ode45(#(t,x) odo(t,x,b,obz,vr,vl), 0:dt:tf, [0;0;0]);
with R15 but keep getting the error:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
How to solve this issue?
You have some syntax errors here. First You can't just type function odo and let the MATLAB guess what it should do here. The second, you call t and x twice in your solver expressions. Be consistent, call function in ode solver this way:
t_span=1:1:12;
b=0.2;
[t, x] = ode45(#odo, t_span, [0;0;0], b);
You don't need to pass t and x manually, solver do it itself. Only the additional parameter b (however it is not in use, in your example). Also in declaration of function do as follow:
function dx = odo(t,x,b)
vr=sin(t); %Non-OD equations here
vl=cos(t);
obz=0.05*sin(t);
n=numel(x); %this generate a holder for results
dx=zeros(n,1);
dx(1) = (vl+vr)/2*cos(x(3)); %All ODEs formatted like this
dx(2) = (vl+vr)/2*sin(x(3));
dx(3) = obz;
As you can see, vr, vl, and obz are time-depended values, so need to be re-calculated in every step of solver. You have to place it in your solver function.

Modelica Class Method

I would like to use a class function/method in my Modelica model as follows:
optimization Moo(objective=-x(finalTime), startTime = 0, finalTime = 12)
parameter Real e = 0.05;
Real x(start=2, fixed=true, min=0, max=100);
input Real v (min=0, max=1);
function omega
input Real t;
output Real y;
algorithm
y := e;
end omega;
equation
der(x) = v*omega(time);
constraint
v<=1;
end Moo;
I would like the variable e in the function omega to be a variable so that I can easily change its value at a later point in time when I am doing a parameter sweep. Unfortunately, the function omega does not seem to know about the variable e and the JModelica compiler returns the error:
Cannot find class or component declaration for e
I would naïvely expect that since omega and e belong to the same class omega would be able to see e.
Is there a way to achieve this?
Member functions are not supported in Modelica, so a function declared inside a model acts like a standalone function without having access to the surrounding model variables.
Member functions are not allowed due to functions need to be pure, i.e. they are not allowed to have any side effect. This is a fundamental assumption in Modelica that makes it possible for a tool to apply symbolic transformation and rearrange calculations.
You can have something like a member function, if you explicitly pass the needed variables as additional input to the function. See this example:
package MemberFunction
model A
Real x=1;
function get_x = MemberFunction.get(u=x);
end A;
function get
input Real u;
output Real y;
algorithm
y := u;
end get;
model Test
A a;
Real x;
equation
x = a.get_x();
end Test;
end MemberFunction;

How to pass a Matlab vector variable to a MuPAD function?

I want to use the stats::swGOFT function in MuPAD. I have a numerical vector called r. I used
feval(symengine, 'stats::swGOFT', r);
The error was
Error using mupadengine/feval (line 157)
MuPAD error: Error: Some data are of invalid type.
So I tried a more direct way, which worked:
feval(symengine, 'stats::swGOFT', 1,2,3,4);
But this didn't work:
feval(symengine, 'stats::swGOFT', [1,2,3,4]);
My variable r is a 1146-by-1 double vector. Obviously I can't manually input all the numbers. So, how to pass the vector variable r to the MuPAD function stats::swGOFT?
MuPAD is not Matlab. From the current version documentation for stats::swGOFT, it appears that this function requires a list, as opposed to an array (what Matlab uses). Many MuPAD functions automatically coerce inputs to the desired format, but that doesn't seem to occur in this case. You have several options if you want to call this function from Matlab using numeric values – here's a simple one that will work for both floating point and symbolic numeric values:
r = randn(1146,1);
rStr = char(sym(r(:).'));
feval(symengine, 'stats::swGOFT', rStr(9:end-2))
This one should perform the string conversion more quickly for large datasets of floating point values using sprintf:
r = randn(1146,1);
rStr = ['[' sprintf('%.17g', r(1)) sprintf(',%.17g', r(2:end)) ']'];
feval(symengine, 'stats::swGOFT', rStr)
Since you're converting to a string yourself, you might as well convert the above to use evalin directly:
r = randn(1146,1);
rStr = [ sprintf('%.17g', r(1)) sprintf(',%.17g', r(2:end)) ];
evalin(symengine, ['stats::swGOFT([' rStr '])'])

matlab coder covert m-file to c++?

I used MATLAB coder to covert M-file to cpp-file.
There generated problem when is building.
Expected either a logical, char, int, fi, single, or double. Found an
mxArray. MxArrays are returned from calls to the MATLAB
interpreter and are not supported inside expressions. They may only be
used on the right-hand side of assignments and as arguments to
extrinsic functions.
MATLAB code :
nms = sum(transpose(X).^2);
nms0=-1 * nms;
nms2=transpose(nms0);
nms3=transpose(X);
nms4=nms2*ones(1,n);
nms5=ones(n,1)*nms;
nms6=2*X*nms3;
nms7=zeros(150,150);
nms7=nms4-nms5; //This line is wrong
nms8=nms7 + nms6;
K = exp(nms8);
I want to know why code has been run correct in MATLAB,but it has error when is building
This error happens when you try to use result of extrinsic functions in expressions. In the code you provided is "n" or "X" the result of an extrinsic function? Even if they are not directly a result of an extrinsic function, they may have been computed based on data from other extrinsic functions.
One way to fix the problem is to help MATLAB coder convert these extrinsic data to known types. You can do that by pre-defining them with known data. For example,
coder.extrinsic('some_extrinsic_fcn');
y = zeros(10,1);
y = some_extrinsic_fcn();
y = y * 2;
In this case some_extrinsic_fcn should return a double precision vector with 10 elements. This resulting mxArray will be auto-converted and stored in y. Without the line "y = zeros(10,1);" y will be of mxArray type and the line "y = y * 2;" will cause an error.

How do I make a function from a symbolic expression in MATLAB?

How can I make a function from a symbolic expression? For example, I have the following:
syms beta
n1,n2,m,aa= Constants
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If I want to use f in a special program to find its zeroes, how can I convert f to a function? Or, what should I do to find the zeroes of f and such nested expressions?
You have a couple of options...
Option #1: Automatically generate a function
If you have version 4.9 (R2007b+) or later of the Symbolic Toolbox you can convert a symbolic expression to an anonymous function or a function M-file using the matlabFunction function. An example from the documentation:
>> syms x y
>> r = sqrt(x^2 + y^2);
>> ht = matlabFunction(sin(r)/r)
ht =
#(x,y)sin(sqrt(x.^2+y.^2)).*1./sqrt(x.^2+y.^2)
Option #2: Generate a function by hand
Since you've already written a set of symbolic equations, you can simply cut and paste part of that code into a function. Here's what your above example would look like:
function output = f(beta,n1,n2,m,aa)
u = sqrt(n2-beta.^2);
w = sqrt(beta.^2-n1);
a = tan(u)./w+tanh(w)./u;
b = tanh(u)./w;
output = (a+b).*cos(aa.*u+m.*pi)+(a-b).*sin(aa.*u+m.*pi);
end
When calling this function f you have to input the values of beta and the 4 constants and it will return the result of evaluating your main expression.
NOTE: Since you also mentioned wanting to find zeroes of f, you could try using the SOLVE function on your symbolic equation:
zeroValues = solve(f,'beta');
Someone has tagged this question with Matlab so I'll assume that you are concerned with solving the equation with Matlab. If you have a copy of the Matlab Symbolic toolbox you should be able to solve it directly as a previous respondent has suggested.
If not, then I suggest you write a Matlab m-file to evaluate your function f(). The pseudo-code you're already written will translate almost directly into lines of Matlab. As I read it your function f() is a function only of the variable beta since you indicate that n1,n2,m and a are all constants. I suggest that you plot the values of f(beta) for a range of values. The graph will indicate where the 0s of the function are and you can easily code up a bisection or similar algorithm to give you their values to your desired degree of accuracy.
If you broad intention is to have numeric values of certain symbolic expressions you have, for example, you have a larger program that generates symbolic expressions and you want to use these expression for numeric purposes, you can simply evaluate them using 'eval'. If their parameters have numeric values in the workspace, just use eval on your expression. For example,
syms beta
%n1,n2,m,aa= Constants
% values to exemplify
n1 = 1; n2 = 3; m = 1; aa = 5;
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If beta has a value
beta = 1.5;
eval(beta)
This will calculate the value of f for a particular beta. Using it as a function. This solution will suit you in the scenario of using automatically generated symbolic expressions and will be interesting for fast testing with them. If you are writing a program to find zeros, it will be enough using eval(f) when you have to evaluate the function. When using a Matlab function to find zeros using anonymous function will be better, but you can also wrap the eval(f) inside a m-file.
If you're interested with just the answer for this specific equation, Try Wolfram Alpha, which will give you answers like:
alt text http://www4c.wolframalpha.com/Calculate/MSP/MSP642199013hbefb463a9000051gi6f4heeebfa7f?MSPStoreType=image/gif&s=15
If you want to solve this type of equation programatically, you probably need to use some software packages for symbolic algebra, like SymPy for python.
quoting the official documentation:
>>> from sympy import I, solve
>>> from sympy.abc import x, y
Solve a polynomial equation:
>>> solve(x**4-1, x)
[1, -1, -I, I]
Solve a linear system:
>>> solve((x+5*y-2, -3*x+6*y-15), x, y)
{x: -3, y: 1}