How do I pass variables between functions
Show older comments
This should be trivial, but I keep getting errors.
This is my main function. It calls each function to read data from a .txt file.
function [] = int_main
%opens example file and calls all functions to read from it
FEA=fopen('FEA.txt');
readMesh(FEA);
readProperties(FEA);
readConstraints(FEA);
readLoads(FEA);
assembleGlobalStiffnessMatrix()
end
This is an example of one of the functions.
function [Properties] = readProperties(FEA)
%Reads the material properties about the beam
format shorteng
Properties= fscanf(FEA,'%*s %*s %*s %g %g %g',[3,1])'
end
Now, the problem is when I try to use the "Properties" variable in the assembleGlobalStiffnessMatrix. It is not in the same workspace.
function [] = assembleGlobalStiffnessMatrix(Properties)
% Sets up Stiffness Matrix
Properties
end
All I need to do is use the variable I calculated from the previous function. Other answers have suggested using a function function, but I don't think this will work because executing the readProperties function in the globalStiffnessMatrix function will cause the fscanf command to read the wrong line.
Somehow, I need to access the "Properties" variable. But my assignment specifies that global variables are prohibited. So, I have no idea how to make this work.
Thank you
2 Comments
jgg
on 6 Jul 2016
You have to pass things into the function you want and store output you want to store. So, in your workflow, you'd want something like this:
function [] = int_main
%opens example file and calls all functions to read from it
FEA=fopen('FEA.txt');
readMesh(FEA);
Properties = readProperties(FEA);
readConstraints(FEA);
readLoads(FEA);
assembleGlobalStiffnessMatrix(Properties)
end
Michael cornman
on 6 Jul 2016
Answers (1)
Honglei Chen
on 6 Jul 2016
It seems you didn't explicitly return and pass in the properties you computed? Could you try
properties = readProperties(FEA);
assembleGlobalStiffnessMatrix(properties)
in your main function?
HTH
Categories
Find more on Whos in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!