How to preallocate when final numbers of rows in unknown
1 回表示 (過去 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
0 件のコメント
採用された回答
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 Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!