How can I automatically create n variables in a matlab function
32 次查看(过去 30 天)
显示 更早的评论
For the function J_n = Jacobian(n) the user input is n. For each n I want matlab to create a new variable called J_n. For example n=3 returns 3 variables called J_1, J_2 and J_3. Each J_n is a vector containing vectors of Tn' (al T's are already declared in another function don't worry about them). For example n=3 gives J_1 = [T_1' T_0' T_0'] and J_2 = [T_1' T_2' T_0'] and J_3 = [T_1' T_2' T_3']. Note that for n=5 each J_n wil consist of 5 Tn's in stead of 3 Tn's. I tried using for loops, but I was not able to make the name of a variable function dependent.
1 个评论
Stephen23
2015-9-30
编辑:Stephen23
2015-9-30
It is a poor programming practice to generate variable names dynamically and make variables magically pop into existence. Avoid doing this in any programming language.
If you want to know why this is a bad programming practice then read my answer carefully, and all of the linked pages. You might like to research this topic yourself, you will find plenty of discussions online.
回答(2 个)
Stephen23
2015-9-30
编辑:Stephen23
2019-6-19
3 个评论
John D'Errico
2015-9-30
编辑:John D'Errico
2015-9-30
Yes. There is the option to add a comment! Click on the link that says "Comment on this Answer". I've moved your comment to a true comment.
"note: there was no option to comment to the answer of stephen. Thank you for your effort. I accept that dynamic variable names are a bad idea. However I can still not find a solution for my code. Assume I have physical system that can be discribed as M*a=F. M is a matrix. This matrix is a sum of M_0 to M_n. n is the number of degrees of freedom (DoF) for this system, it also is a user input. M_i=J_i*I_i. So I need a different J_i for each M_i and I need to be able to find this J_i. However I dont 'know' what this J_i looks like, because its size and content is dependent on te number of DoF. If generating dynamic variable names is a bad idea, how else am I suppose to 'find' my variable while implementing them in an other variable? Cells and tables etc wont let me do this. Please imagine your old physics exams but now generated automatically by only giving the configuration of the joints and the masses. It really shouldn't be that hard."
WAT
2015-9-30
编辑:WAT
2015-9-30
As far as I can tell a cell array will absolutely do what you want it to. For example,
A = cell(1,2);
A(1) = {[1,2]};
A(2) = {[1,2;3,4]};
% etc
Creates a cell array with two different size matrices. To get them out so you can do math with them, just use { }, eg
A2 = eye(2)*A{2}
4 个评论
WAT
2015-10-1
Why wouldn't
A{n} = function_that_generates_A(n);
do what you want? Is your issue that you don't know how to generate your A_n matrices, or that you don't know how to store them once you've generated them?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!