Multiple outputs from a function in a for loop
22 views (last 30 days)
Show older comments
I'm trying to get multiple outputs from a function in a for loop, and am instead getting multiple columns of the same output. The function within the for loop gives me the correct output when I run the function once (with two different output variables), but does not give the correct output when nested in the for loop.
Here's the code:
function [e, s] = stressstrain(Nodes, u, MatSet, ElmConnect)
[r,c] = size(ElmConnect);
e = zeros(r, 1);
s = zeros(r, 1);
for b = 1:r
%define the nodes and material set for each element
node1_no = ElmConnect(b,1);
node2_no = ElmConnect(b,2);
mat_set_no = ElmConnect(b,3);
% define the variables needed to run barstiffness.m
node1 = Nodes(node1_no,:);
node2 = Nodes(node2_no,:);
modulus = MatSet(mat_set_no,1);
% find nodal displacements per node coordinates
u1 = u(node1_no,:);
u2 = u(node2_no,:);
% run bar stress/strain for each element and add to global system
[E, S] = barstressstrain(node1, u1, node2, u2, modulus);
e(b) = E;
s(b) = S;
end
end
And here's the second function barstressstrain:
function [e, s] = barstressstrain(node1, u1, node2, u2, modulus)
% original element length
diff = node2-node1;
L = sqrt(diff(1)^2 + diff(2)^2 + diff(3)^2);
Cx = (node2(1) - node1(1)) / L;
Cy = (node2(2) - node1(2)) / L;
Cz = (node2(3) - node1(3)) / L;
% using the formula given in Logan textbook...
U = [u1' ; u2'];
C = [-Cx -Cy -Cz Cx Cy Cz];
s = (modulus / L) * C * U;
e = s/modulus;
end
When I run this barstressstrain.m for the first element (should be the first row of the matrix results from stresstrain.m, I get the output [-0.5, -2.5]. When I run the function stressstrain.m, the output of the first row is [-0.5, -0.5]. Why am I getting only the first variable for both columns?
Any help is appreciated!
0 Comments
Answers (1)
Matt J
on 25 Sep 2013
Assuming you fed the same input data to barstreesstrain in both cases, I can see no reason why they'd be different. However, we have no way of verifying that that's what you did!
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!