Using a matrix as an input argument for a function

22 vues (au cours des 30 derniers jours)
Thiran
Thiran le 23 Fév 2014
Commenté : Stephen23 le 11 Juil 2019
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

Réponses (4)

Image Analyst
Image Analyst le 23 Fév 2014
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 le 23 Fév 2014
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 le 23 Fév 2014
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 commentaires
Thiran
Thiran le 23 Fév 2014
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 le 23 Fév 2014
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;

Connectez-vous pour commenter.


Mohit Kumar
Mohit Kumar le 11 Juil 2019
try this
[y;z;Vy;Vz]=x;
  1 commentaire
Stephen23
Stephen23 le 11 Juil 2019
@Mohit Kumar: please provide a link to the documentation, where this syntax is explained?:
[y;z;Vy;Vz]=x;

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by