I need help preallocating array?

I need help making this array preallocated.
p = 10;
newArray = [];
array = [];
for i = 1:p
a= variable1;
b = variable2;
c = variable3;
d = variable4;
e = variable5;
array = [a,b,c,d,e]
newArray= [newArray array];
end

 Réponse acceptée

pfb
pfb le 12 Avr 2015

0 votes

Look at the function "zeros".
array = zeros(1,5);
newArray = zeros(1,5*p);
and, in the loop
newArray((1+(i-1)*5):(i*5))=array;
This way all you need is allocated before the loop.
I assume that the assignments of a through e come from function that have a different value for different i's.
If they are the same, it's just a tiling problem. You need "repmat".

5 commentaires

ME
ME le 12 Avr 2015
Thank you soooo much thats really helpful. could you please explain this newArray((1+(i-1)*5):(i*5))=array; so i am able to manipulate it to suit my program. because I want this to create rows = p which in my case in 10.
pfb
pfb le 12 Avr 2015
well, it's simply what you want to do, I guess.
At the ith iteration you put the content of "array" into the elements of newArray going from 1+(i-1)*5 to (i*5).
That is:
- when i = 1 the elements go from 1 to 5 - when i = 2 the elements go from 6 to 10 - and so on
This avoids concatenating array at the end of newArray, which in general slows you down.
But now you talk of rows.. What exactly do you want to attain here? Should newArray be a very long row vector or a p by 5 matrix?
ME
ME le 12 Avr 2015
I want new array to be 5 columns and 'p' rows.
ME
ME le 12 Avr 2015
in my original loop the reason i have
myArray = [myArray array];
was so that in each iteration array in copied in new row.
pfb
pfb le 12 Avr 2015
Modifié(e) : pfb le 12 Avr 2015
not really in a new row.
In your code "array" is copied at the end of the row vector newArray. No new rows.
Use the semicolon operator to add new rows. You should have written
myArray = [myArray; array];
I think you should read some documentation.
Anyway, to allocate your matrix (not vector)
newArray = zeros(p,5);
Filling it, now is much simpler. This fills the ith row of newArray with the current values in array.
newArray(i,:) = array;
You should state your problem better. Apparently, what you needed was filling the rows of a matrix, all the time.
And perhaps take a look into the basics of matlab.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Centre d'aide et File Exchange

Question posée :

ME
le 12 Avr 2015

Modifié(e) :

pfb
le 12 Avr 2015

Community Treasure Hunt

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

Start Hunting!

Translated by