Borrar filtros
Borrar filtros

How to preallocate when final numbers of rows in unknown

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 28 de Abr. de 2020
Editada: Ameer Hamza el 28 de Abr. de 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 comentarios
Austin Hernandez
Austin Hernandez el 28 de Abr. de 2020
Thank you! This fix actually worked for my purposes.
Ameer Hamza
Ameer Hamza el 28 de Abr. de 2020
I am glad to be of help.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by