How to preallocate when final numbers of rows in unknown

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Ameer Hamza
Ameer Hamza il 28 Apr 2020
Modificato: Ameer Hamza il 28 Apr 2020
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 Commenti
Austin Hernandez
Austin Hernandez il 28 Apr 2020
Thank you! This fix actually worked for my purposes.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by