Pre-allocate memory to zeros or NaN?

36 Ansichten (letzte 30 Tage)
Lina Koronfel am 5 Aug. 2021
Kommentiert: Lina Koronfel am 5 Aug. 2021
I'm dealing with large matrix size in a for loop and I currently pre-allocate the matrix to zeros before the for loop, however, this causes me some problems with some math equations I must apply on the matrix. So my question is, does pre-allocating the memory to a NaN matrix recommended? or does MATLAB not like that?
Update for clarification:
Example:
a=zeros(5,5)
for j=1:4:5
v=j;
a(:,j)=v+10;
end
So the problem is if I want to do any calculation with the rows, I will end up including rows 2,3,4 which are now 0, this messes up with my calculations. So I want to explore the option of creating a NaN matrix and using 'omitnan' in my calculations.
2 KommentareKeine anzeigenKeine ausblenden
KSSV am 5 Aug. 2021
It depends on what numbers you are going to fill into matrix. If you fill with zeros what problem it is causing? First what for the loop is?
Lina Koronfel am 5 Aug. 2021
The numbers are double precision. The problem is that I'm skipping some trials, so here is a quick example:
a=zeros(5,5)
for j=1:4:5
v=j;
a(:,j)=v+10;
end
So the problem is if I want to do any calculation with the rows, I will end up including rows 2,3,4 which are now 0, this messes up with my calculations. I know there is an option of skiiping every forth row but I don't want to do that because The code is pretty big and I would have to go to every line and change it. So I want to explore the option of creating a NaN matrix and using 'omitnan' in my calculations.
Please let me know if this is recommended, and if there is any harm if using NaN for pre-allocation. Thank you

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Chunru am 5 Aug. 2021
Bearbeitet: Chunru am 5 Aug. 2021
If you have skipped some data and want to omit those data later on, then the preallocation with nan is a better options. Especially if you want to use some matlab built in functions (such as mean, std), options are available to omit nans. NaN is the part of IEEE arithmetic representation, it should not have side effect on preallocatio. The only side-effect is when performing calculation (NaN+2=Nan), but you are prepared to ignore NaNs.
1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Lina Koronfel am 5 Aug. 2021
Great!! Thank you for the explanation :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Sulaymon Eshkabilov am 5 Aug. 2021
Of course, you can do memory allocation with nan() as well alike zeros(), e.g.:
k=10; m=15;
M = nan(k, m);
...
1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Lina Koronfel am 5 Aug. 2021
Thank you!!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by