How can I prealloate a comlex-valued matrix?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hanna Liu
am 12 Sep. 2019
Bearbeitet: Matthew Bayer
am 22 Sep. 2021
The following code seems really slow, which I do allocating a matrix and then write some complex numbers in it:
tic,for kk = 1:1000
aa = (zeros(10000,500)); aa(:,300) = 1i * 3;
end;toc
The code is really slow:
Elapsed time is 42.463659 seconds.
Is there any way to accerlate this?
4 Kommentare
Bruno Luong
am 12 Sep. 2019
Bearbeitet: Bruno Luong
am 12 Sep. 2019
"When I run the matlab profiler, I find out that the code I first write values in my matrix is super slow. "
MATLAB has complicated memory management than you would think. It can allocate and copy a big array when you assign something even tiny (copy-on-write). It can do nothing when you think you allocate a big array, but then the first time you read something it will allocated (allocate-on-use).
It is crucial for you to describe how you allocate, if your matrix is "shared" by something else, etc... or the data flow of your algorithm so we can advide.
You cannot make a simplify your code and ask for the advise based on the simplification, especially "how to allocate faster than zeros(...)", no there is NO simple answer to such question, because the time depends what your program did before.
Akzeptierte Antwort
Steven Lord
am 12 Sep. 2019
I would probably use the 'like' syntax for the zeros function.
A = zeros(10000, 500, 'like', 1i);
1 Kommentar
Matthew Bayer
am 22 Sep. 2021
Bearbeitet: Matthew Bayer
am 22 Sep. 2021
This is better than the other answer, A = complex(zeros(10000,500)). I recently tried both and found the 'like' syntax was considerably faster. The complex() statement is presumably first creating the real array and then converting to a complex one, while the 'like' syntax just creates the complex array right away.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Historical Contests 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!