how to preallocate a variables

21 views (last 30 days)
How do I preallocate variable in this code, when they are inside different functions? Thanks
In general it looks like this:
Script:
A=0:1300;
for i=1:10:length(B)
[]=function1()
end
Function1:
B=0:133;
for i=1:length(B)
[]=function2()
end
Function2:
C= xlsread()
D=1:129
for i=1:length(D)
Variables (c)
[]=function3(Variables (c))
end
  3 Comments
Asliddin Komilov
Asliddin Komilov on 21 Jul 2019
Edited: Asliddin Komilov on 21 Jul 2019
that is the catch, output variables in the most inner function come out as the output variables of the most outer function, indexes of the variables in different functions is different inside and outside of the functions, according to the eparchy. Preallocating all variables takes space, because they are not deleted after function runs. I hope this is now more understandable:
A=0:1300;
for i=1:10:length(A)
[m,n,c,D,B]=function1(A)
end
Function1:
B=0:133;
for i=1:length(B)
[m,n,c,D]=function2(A,B)
end
Function2:
C= xlsread()
D=1:129
for i=1:length(D)
Variables (c)
[m,n,c]=function3(Variables (A,B,D,c))
end

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 21 Jul 2019
Again, with the code you show, there's nothing that can be preallocated. But your loops are also not very useful since the overwrite the output variable on each step. So, perhaps your question is not about preallocation but how to keep all the values returned by the loop (where indeed you would use preallocation to make the code more efficient).
In that case, it's simple you need to index the variables you assign to. Depending on the size/shape of the outputs your indexing is going to look different, so again, more details required.
Assuming the outputs are scalar:
steps = 1:10:1301;
%preallocation advised but not required:
m = zeros(1, numel(steps));
n = zeros(1, numel(steps));
c = zeros(1, numel(steps));
D = zeros(1, numel(steps));
B = zeros(1, numel(steps));
%or they can all be preallocated at once with:
[m, n, c, D, B] = deal(zeros(1, numel(steps)));
%looping
for i = steps
[m(i), n(i), c(i), D(i), B(i)] = function1(something);
end
  7 Comments
Asliddin Komilov
Asliddin Komilov on 24 Jul 2019
I thank you very much for your assistance, but somehow it did not help much, so I opened another question:

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2016a

Community Treasure Hunt

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

Start Hunting!