Using a matrix as an input argument for a function

26 次查看(过去 30 天)
Hello,
I'm currently trying to solve a problem in Matlab that involves using two input arguments in a function, one of which is a matrix. My problem is that within the Matrix are the variables y, z, Vy and Vz which Matlab recognises as undefined.
The code I'm having trouble with is this:
[dotx]=me12ttdP4(t, x)
x=([y;z;Vy;Vz]);
Vdoty=(K2(z-y)+B(Vz-Vy))/M;
Vdotz=(K1(u-z)+K2(z-y)-B(Vz-Vy))/m;
Ydot=Vy;
Zdot=Vz;
dotx=[Ydot;Zdot;Vdoty;Vdotz];
I get the error in the command window when I input
>> me12ttdP4(3, [1;2;0;3])
The error is:
Undefined function or variable 'y'.
Error in me12ttdP4 (line 6)
x=([y;z;Vy;Vz]);
Thank you for your time

回答(4 个)

Image Analyst
Image Analyst 2014-2-23
Why do you think that the me12ttdP4() function should know what y is when you didn't pass it in or define it inside me12ttdP4() itself? It won't know what it is until you give it a value.

Thiran
Thiran 2014-2-23
The variable y, z, Vy and Vz don't have a constant value. The input of:
>> me12ttdP4(3, [1;2;0;3])
into the main window is just to test whether or not the script genereates a vector for dotx.

Sagar Damle
Sagar Damle 2014-2-23
I think,this will give you correct answer.
[dotx]=me12ttdP4(t, x)
y = x(:,1); z =x(:,2); Vy =x(:,3); Vz =x(:,4);
Vdoty=(K2(z-y)+B(Vz-Vy))/M;
Vdotz=(K1(u-z)+K2(z-y)-B(Vz-Vy))/m;
Ydot=Vy;
Zdot=Vz;
dotx=[Ydot;Zdot;Vdoty;Vdotz];
But my question is - you have not defined values of K1,K2,M and m in function definition of 'mel2ttdP4()'.How can you get correct output without this? Oh,are these global variables or such a thing?
  4 个评论
Thiran
Thiran 2014-2-23
I tried your solution and got the error:
Attempted to access x(:,2); index out of bounds because size(x)=[4,1].
Error in me12ttdP4 (line 6)
y=x(:,1); z=x(:,2); Vy=x(:,1); Vz=x(:,1);
So I switched it around a bit to:
y=x(1,:); z=x(2,:); Vy=x(3,:); Vz=x(4,:);
this now produced the error:
Index exceeds matrix dimensions.
Error in me12ttdP4 (line 23)
Vdoty=(K2(z-y)+B(Vz-Vy))/M;
Sagar Damle
Sagar Damle 2014-2-23
Sorry for my mistake! I think you want to get product of two terms - K2 and (z-y).So you have to write this as below -
Vdoty=(K2*(z-y)+B*(Vz-Vy))/M;
Similarly, Vdotz=(K1*(u-z)+K2*(z-y)-B*(Vz-Vy))/m;

请先登录,再进行评论。


Mohit Kumar
Mohit Kumar 2019-7-11
try this
[y;z;Vy;Vz]=x;

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by