how can i fix this code

7 visualizaciones (últimos 30 días)
Johny
Johny el 18 de Dic. de 2022
Comentada: Johny el 19 de Dic. de 2022
how can i fix this one
sdot= @(t,s) ....
[s(2);
[2*M*s(2)*s(4)*cos(s(3))*sin(s(3))+M*g*cos(s(3))*sin(s(3))-s(4)*L*cos(s(3))+k*s(1)]/(M*sin^2(s(3))+m);
s(4);
[-2*M*s(2)*s(4)*sin(s(3))[cos^2(s(3))-sin^2(s(3))]-sin(s(3))[M*g*cos^2(s(3))-2*m*s(2)*s(4)-g*m-(g+(M*sin^2(s(3)))]+s(4)*L*cos^2(s(3))-k*cos(s(3))]/(L*m+L*M*sin^2(s(3)))];

Respuesta aceptada

Walter Roberson
Walter Roberson el 18 de Dic. de 2022
You need to fix some portions of the code.
sin(s(3))[M*g..etc]
That is invalid.
In MATLAB, the [] operator is used only for array (or vector) building. It can never be used to index a result -- if you want M*g..etc to be used to index the resut of sin(s(3)) then you would need to define a helper function, like
IndexAt = @(EXPRESSION, INDEX) EXPRESSION(INDEX)
sdot= @(t,s) ....
[s(2);
[2*M*s(2)*s(4)*cos(s(3))*sin(s(3))+M*g*cos(s(3))*sin(s(3))-s(4)*L*cos(s(3))+k*s(1)]/(M*sin^2(s(3))+m);
s(4);
[-2*M*s(2)*s(4)*sin(s(3))[cos^2(s(3))-sin^2(s(3))]-INDEXAT(sin(s(3)),M*g*cos^2(s(3))-2*m*s(2)*s(4)-g*m-(g+(M*sin^2(s(3))))+s(4)*L*cos^2(s(3))-k*cos(s(3))]/(L*m+L*M*sin^2(s(3)))];
But it seems very unlikely that the expression given will happen to work out as exactly an integer.
cos^2(s(3))
as far as MATLAB is concerned, that is equivalent to
INDEXAT(cos()^2,s(3))
which would try to invoke cos with no parameters, do a matrix squaring of the result, and index that result as s(3)
If you want to square the cosine then you need to square the result of the cosine call, such as
cos(s(3)).^2
It is recommended that [] not be used to indicate prioritization. You can certainly code things like 5*[x+9,y+7] which would in a sense give priority to calculating x+9 and y+7 before doing the multiplication. But if you had 5*[x+9] then the recommendation would be to instead write 5*(x+9) . 5*[x+9] is not invalid code, but it is not as efficient as it could be, as it is prod(5, horzcat(plus(x,9))) with the matrix-building call to horzcat() present, which is not as efficient as 5*(x+9) would be prod(5, plus(x,9)) with no extra call.
Using [] for prioritization risks unexpect results due to some subtle details of what spacing means inside [] and {} operators. [] is only recommended if you are building lists or arrays.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by