How to use a variable from one for loop in another for loop?
3 views (last 30 days)
Show older comments
Hello,
I would like to use a variable I have created inside a for loop within another for loop without having to redefine it. Here is my code:
Econn = [(1:nn-1)',(2:nn)']; %Connectivity matrix - i.e. 1 connects to 2, 2 connects to 3 etc. The ' symbol produces transpose
for i = 1:ne
indexNodes= Econn(i,:); %Gives the ith row of matrix Econn. It gives the two nodes that should be connected.
ElmtCentre(:,i) = [0.5*sum(NodeX(indexNodes)), 0.5*sum(NodeY(indexNodes))]; %Calculates half of the sum of the two connected nodes. i.e. node 0 and 1 connected therefore ElmtCentre = 0.5
text(ElmtCentre(1,i), ElmtCentre(2,i)+0.05, ['E', num2str(i)]); %Displays text indicating each element visualise it.
Node1 = [NodeX(indexNodes(1)); NodeY(indexNodes(1))];
Node2 = [NodeX(indexNodes(2)); NodeY(indexNodes(2))];
L(i) = norm(Node1-Node2);
end
Sy = 0;
Mz = 0;
for i=1:ne
Fy = L(i)*Qy(i);
Sy = Sy+ - Fy;
R = [ELmtCentre(:,i);0];
F = [0;Fy;0];
Mz = Mz + - cross(R,F);
end
I want to use the ElmtCentre variable in the other for loop shown without having to define indexNodes and ElmtCentre again. However, when this code is run i get the following error message:
'Unrecognized function or variable 'ELmtCentre'.
Error in BendingMomentDistForce (line 30)
R = [ELmtCentre(:,i);0]; '.
Please let me know if this does not make sense.
Thanks.
0 Comments
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!