Performing the for loop written in one function in another function.

Hi everyone,
I'm working on a project for school where we're given several "skeleton" functions which we need to fill in and make all those functions work together in the end.
I have a for loop in one function called "shapeFunctions" that I actually want to run inside another function called "elemStiff".
The for loop in "shapeFunctions" looks like this:
for i = 1:length(xi)
% TODO
N = [(1 - xi(1,i)) * (1 - xi(2,i));
(1 + xi(1,i)) * (1 - xi(2,i));
(1 + xi(1,i)) * (1 + xi(2,i));
(1 - xi(1,i)) * (1 + xi(2,i))] .* 1/4;
dNdxi = [(-1 + xi(2,i)) (-1 + xi(1,i));
(1 - xi(2,i)) (-1 - xi(1,i)) ;
(1 + xi(2,i)) (1 + xi(1,i)) ;
(-1 - xi(2,i)) (1 - xi(1,i))] .* 1/4;
%
end
where xi for the above case is:
xi = [ -1/sqrt(3) 1/sqrt(3) -1/sqrt(3) 1/sqrt(3);
-1/sqrt(3) -1/sqrt(3) 1/sqrt(3) 1/sqrt(3)] ;
And I want to run the following in "elemStiff":
B(1,[1,3,5,7]) = dNdxi(:,1)';
B(2,[2,4,6,8]) = dNdxi(:,2)';
B(3,[1,3,5,7]) = dNdxi(:,2)';
B(3,[2,4,6,8]) = dNdxi(:,1)';
dxdxi = [dNdxi(:,1)' * elemCoord(:,1); dNdxi(:,2)' * elemCoord(:,1)]; % 1st column of Jacobian
dydxi = [dNdxi(:,1)' * elemCoord(:,2); dNdxi(:,2)' * elemCoord(:,2)]; % 2nd column of Jacobian
J = [dxdxi dydxi];
k = k + B' * D * B * det(J) * wList(1) * wList(2);
I could just write the for loop for N and dNdxi in the "elemStiff" function, but that would defeat the purpose of writing the "shapeFunction" function.
Any guidance is appreciated.
Thank you!

4 Comments

You just "call" the desired function inside the other where wanted and assign its outputs to the desired variables -- it goes off and does its thing and returns what it is programmed to do. A user-written function is no different in that regards than a MATLAB-supplied function like MEAN or any other.
I will note, however, that the definition of the LHS variables in the for...end loop shown for the shapeFunctions function is not correct in that it doesn't save vectors for either N or dNdxi but will have only the value for each computed for the last pass through the loop. This is because the LHS variables are not subscripted and so will be just a single value which is overwritten every pass through the loop.
Thank you for the feedback! And yea, the N and dNdxi will keep getting overwritten... How do I prevent this from happening? How do I set the LHS variables so they are subscripted?
Thanks again!
Preallocate and assign subscripts...see the first example in the documentation for for...NB: it sets a 2D array; see the doc for zeros function on why.

Sign in to comment.

Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Release

R2020b

Asked:

on 9 Apr 2021

Commented:

on 9 Apr 2021

Community Treasure Hunt

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

Start Hunting!