How to preallocate when final numbers of rows in unknown

2 次查看(过去 30 天)
Hello, I have a for loop that has 3 options like this:
The issue is that the path of the for loop changes depending on user inputs (if they enter 2, then e = 3x and so on). Thing is, I don't know how many rows I'll end up with for each variable as it can change with each cycle of the inputs
a = 1; b = 1; c = 1;
x = 0:1:10
n=5
%preallocating
e = zeros(?,10)
p = zeros(?,10)
o = zeros(?,10)
for i = 1:n
if x == 2
e(a,:) = 3x
elseif y == 15
p(b,:) = 100/x
else
o(c,:) = 2+x
end
end

采纳的回答

Ameer Hamza
Ameer Hamza 2020-4-28
编辑:Ameer Hamza 2020-4-28
If you don't already know the size of your matrix, then you can make a guess about what will be the maximum size, and you allocate according to that. If fewer numbers of rows are used, then you can delete the extra rows or columns at the end. If more are used, then you can again grow your matrix by a suitable factor until it gets filled again and continue this process.
It can be a bit complicated to implement it in your code; therefore, as a workaround, you can use this FEX submission by John: https://www.mathworks.com/matlabcentral/fileexchange/8334-incremental-growth-of-an-array-revisited. It automatically increases and decreases the size of the array according to your requirement, and you don't need to worry about specifying the maximum matrix size. You can read the description and example on the documentation page of this FEX submission.
  7 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by