Multiple outputs from a function in a for loop

22 views (last 30 days)
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!

Answers (1)

Matt J
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!
  2 Comments
Sarah
Sarah on 25 Sep 2013
I did feed the same input into both. I would give the numbers I input but its generated from a master function that includes 5 other functions (whose outputs have all been checked). But from the code that is there, you cannot see any reason why it would only be returning one output of the function?
Matt J
Matt J on 25 Sep 2013
Edited: Matt J on 25 Sep 2013
Nope.
Just give us the direct inputs to barstressstrain, i.e., set a breakpoint at the line
[E, S] = barstressstrain(node1, u1, node2, u2, modulus);
and when the code stops there, inspect and give us the values of node1, u1, node2, u2, modulus.

Sign in to comment.

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!