Creating arrays in auxiliary functions

Hello.
This is how I have my code organized:
function main()
...
function auxiliary1()
...
function auxiliary2()
...
etc..
When I create an array, A(k) inside one of the auxiliary functions, as k increases the previous values of A turn into zero. Does this means that I can only construct an array inside the main function (where k is counting)?
Thank You

Answers (2)

If you want your variable k to be seen by all your functions, declare it as global in each function, or pass the variable k as input argument in each function

7 Comments

I didn't mention it, but I was already doing that:
function [something] = auxiliary(k).
Then, what is your problem?
The problem is what I said in the beginning. I was pretty sure that using the variable k as input argument, I wouldn't have this problem. However, this is not the case. For example, if k = 1,2,3,4,5, the array A(k) turns something like: A = [0 0 0 0 value]. However, I kknow for sure that the zeros are wrong.
Maybe you need also to use A as input argument. Without your code it's difficult to guess
Using A as input argument is possible. Just need to use an initial guess. I'll put an example of the code here.
function main()
...
...
while t<=tf
x_T = getCoordTransf(Ehat,AA,BB,CC,k);
t = t + dt;
k = k+1;
end
function x_T = getCoordTransf(Ehat,AA,BB,CC,k)
pointA = [0, 0, 0];
pointB = [Ehat(1,1), Ehat(2,1), ((-1)*AA*Ehat(1,1)+(-1)*BB*Ehat(2,1))/CC];
if k == 1
pointC = [6E6,6E6,((-1)*AA*6E6+(-1)*BB*6E6)/CC];
else
pointC=[Ehat(1,2),Ehat(2,2),((-1)*AA*Ehat(1,2)+(-1)*BB*Ehat(2,2))/CC];
end
v1 = pointB - pointA; % Vetor Direção 1
v1 = v1/norm(v1); % Normalização do Vetor Direção 1
v3 = cross(v1,pointC-pointA); % Vetor Direção 3
v3 = v3/norm(v3); % Normalização do Vetor Direção 3
v2 = cross(v3,v1); % Normalização do Vetor Direção 2
x_T(k) = dot(([Ehat(1,k),Ehat(2,k),((-1)*AA*Ehat(1,k)+(-1)*BB*Ehat(2,k))/CC]-pointA),v1);
Ok, what is your question?
As you see, I am creating x_T(k) in the getCoordTransf function. I call that function inside a while loop, in the main function. However, when I ask to "see" x_T (after the loop), all it's members are zero, except the last one. I've already figured an alternative (not very elegant). Thank you.

Sign in to comment.

1 Comment

In main(), do this
x_T(k) = getCoordTransf(Ehat,AA,BB,CC,k);
In getCoordTransf(), do this:
x_T = dot((...........

Sign in to comment.

Asked:

on 13 Jul 2014

Commented:

on 13 Jul 2014

Community Treasure Hunt

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

Start Hunting!