Problem with a function

2 views (last 30 days)
Guido De Angelis
Guido De Angelis on 20 May 2015
Commented: Walter Roberson on 20 May 2015
hi,
that's my problem (excuse me I'm a beginner with matlab!)
I introduce the input variables in my workspace x=[1;2;3;4]; t=5;
and I give a numerical value to the others constants that are in the next function (for example K1=1 m=1,2 etc...)
then I write in my command window
(x,t)
where the function is
function xdot = Fun1(x,t)
global K1 m M K2 w F2 c2 c1 g X;
A=[0,0,0,1;0,0,1,0;K1/m,-K1/m,-c1/m,c1/m;-K2/M-K1/M,K1/M,c1/M,-c1/M-c2/M];
B=[0;0;X*g*sin(w*t);-F2/M-X*g*sin(w*t)];
xdot=A*x+B;
end
In substance I expect to get in output a column vector with four lines but I obtain it with only two lines
someone could help me? Thank you in advance!

Accepted Answer

Star Strider
Star Strider on 20 May 2015
I don’t see the problem. When I run it (with arbitrary constants instead of the global call but otherwise the same code), I get a (4x1) vector.
However I encourage you to avoid global variables. Pass them as extra parameters instead:
function xdot = Fun1(x, t, K1, m, M, K2, w, F2, c2, c1, g, X)
A=[0,0,0,1;0,0,1,0;K1/m,-K1/m,-c1/m,c1/m;-K2/M-K1/M,K1/M,c1/M,-c1/M-c2/M];
B=[0;0;X*g*sin(w*t);-F2/M-X*g*sin(w*t)];
xdot=A*x+B;
end
Then call it from your script or from your ODE solver as:
[K1, m, M, K2, w, F2, c2, c1, g, X] = deal(1, 1, 2, 2, 3, 3, 2, 2, 3, 3); % Define Constants
x=[1;2;3;4]; t=5;
Fun2 = @(x,t) Fun1(x, t, K1, m, M, K2, w, F2, c2, c1, g, X);
output = Fun2(x,t)
that here produces:
output =
4.0000
3.0000
6.8526
-12.8526
  1 Comment
Walter Roberson
Walter Roberson on 20 May 2015
The cause of the problem is the use of global variables. In particular the use of global variables that have not been assigned a value and so continue to have the value [].

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 20 May 2015
If either w or t are empty (as is the case by default for all global variables that have not been otherwise assigned a value), then sin(w*t) would be empty, and then X*g*sin(w*t) would be empty, and then -F2/M-X*g*sin(w*t) would be empty. When you concatenate empty results, the emptiness is "squeezed out", so the result of your concatenation of the four items would be just the two 0's.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!