storing a matrix using new variables established by 'eval'

2 vues (au cours des 30 derniers jours)
Franco
Franco le 3 Fév 2011
I am trying to get a for loop introduce a new variable for every loop using the 'eval' function and store a matrix in the new variable.
elements = 3;
nodes = 2;
phi = [pi / 3,pi-pi/3,0];
for i = 1:elements
eval(['stiffness_' num2str(i) '=zeros(2)'])
eval(['stiffness_' num2str(i) '=[(cos(phi(i)))^2,sin(phi(i)) * cos(phi);sin(phi(i)) * cos(phi(i)),(sin(phi(i)))^2]'])
end
but it's not working. Anyone out there know how to do this?

Réponse acceptée

the cyclist
the cyclist le 3 Fév 2011
There were two syntax errors:
  • Extra bracket at the end of the last line.
  • In one of the terms, you forgot to index into phi(i), using instead just "phi".
More importantly, there is a much better way to code this, using cell arrays. (Notice, in my code below, the curly brackets indexing into the variable "stiffness".) Search the documentation for "cell array" for details. You'll be glad you did.
elements = 3;
nodes = 2;
phi = [pi / 3,pi-pi/3,0];
for i = 1:elements
stiffness{i}=zeros(2)
stiffness{i}=[cos(phi(i))^2,sin(phi(i)) * cos(phi(i));sin(phi(i)) * cos(phi(i)),sin(phi(i))^2]'
end
There is also a good explanation here:
  1 commentaire
Franco
Franco le 3 Fév 2011
That really is much better...thanks a bunch!

Connectez-vous pour commenter.

Plus de réponses (1)

Jiro Doke
Jiro Doke le 3 Fév 2011
I think you asked a similar question here.
There are better ways to do this. Take a look at the answers presented in your other post.
  2 commentaires
Franco
Franco le 3 Fév 2011
I know I can store the variables in a vector, but I really need them as serate variables. Eventually they turn into matrices and things get complicated if they aren't kept separate.
Jan
Jan le 20 Mai 2011
@Franco: A CELL vector seems to be the best soltution for your problem.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by