MATLAB Answers

0

How can I prealloate a comlex-valued matrix?

Asked by Hanna Liu on 12 Sep 2019
Latest activity Edited by Bruno Luong
on 12 Sep 2019
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 Comments

Show 1 older comment
Your code does not make much sense.
  • No array preallocation before the loop. Its that intentional?
  • No indexing to store the results of each iteration.
  • No use of the loop variable kk.
It is not clear what you want to achieve, nor how array preallocation would fit into this.
I think I didn't really explain my problem clear enough in the original description. I am currently working on a function, in which I need to compute a large complex-valued matrix column by column. When I run the matlab profiler, I find out that the code I first write values in my matrix is super slow.
The code I provide in the orignal description is just a simplified example of my current problem. The second line of the following is much slower:
aa = (zeros(10000,500)); aa(:,300) = 3;
bb = (zeros(10000,500)); bb(:,300) = 1i * 3;
I wonder if there is some faster way to work with large complex-valued matrix.
Many thanks for your comments!
"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.

Sign in to comment.

2 Answers

Answer by Steven Lord
on 12 Sep 2019
 Accepted Answer

I would probably use the 'like' syntax for the zeros function.
A = zeros(10000, 500, 'like', 1i);

  0 Comments

Sign in to comment.


Answer by Stephen Cobeldick on 12 Sep 2019
Edited by Stephen Cobeldick on 12 Sep 2019

"How can I prealloate a comlex-valued matrix?"
A = complex(zeros(10000,500));
... your loop here

  0 Comments

Sign in to comment.