Filter löschen
Filter löschen

How to preallocate when final numbers of rows in unknown

3 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by