Cannot pre-allocate an empty matrix?

2 vues (au cours des 30 derniers jours)
Tuvshee
Tuvshee le 14 Mai 2018
Modifié(e) : Stephen23 le 14 Mai 2018
Hello, I'd like to create a matrix that increases with every loop by concatenation the matrix to itself, starting from an empty matrix as shown below
Q1s = [];
alphas = [];
for y = ymin:0.5:ymax
x = (xmin:2.5e-13:xmax)';
Q1s = vertcat(Q1s,x);
alphas = vertcat(alphas,ones(size(x))*y);
end
Now I'm getting the famous "consider pre-allocating for speed" message. But I need Q1 and alpha to be empty matrices to begin with because I'm using vertcat. Is there a way to go about this?

Réponse acceptée

Stephen23
Stephen23 le 14 Mai 2018
Modifié(e) : Stephen23 le 14 Mai 2018
There are many ways:
  1. tell the editor to ignore the warning: right click, "suppress ... on this line"
  2. use a preallocated cell array, concatenate after the loop.
  3. figure out the final size (the total number of elements you require is just numel(x)*numel(y)).
  4. use simpler, more efficient code:
[Q1s,alphas] = ndgrid(xmin:2.5e-13:xmax,ymin:0.5:ymax);
Q1s = Q1s(:);
alphas = alphas(:);
Those three lines give the exactly same output as your code, yet avoids all the bother of loops and expanding arrays and all that jazz.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by