how to preallocate a variables
21 views (last 30 days)
Show older comments
Asliddin Komilov
on 20 Jul 2019
Commented: Asliddin Komilov
on 24 Jul 2019
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
Accepted Answer
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
More Answers (0)
See Also
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!