Preallocating array without adding after the allocating or removing the allocating

1 visualización (últimos 30 días)
So I have a for loop, and every time it have run that loop I want a value to store in an array.
score=zeros(1, again);
for j=1:again
[...]
while(..)
[...]
end
score=[score,tries]
end
So you enter a value for 'again' when you run the function, and at the end of the for loop it takes the 'tries' and store it in 'score'. Problem is that this code increase 'score' size, so first I get zeros and then the score start. I need to change 'score=[score,tries]' so it doesn't add 'tries' at the start/end of the vector nor so it removes the allocating.

Respuesta aceptada

Star Strider
Star Strider el 20 de Abr. de 2015
If you want to add ‘tries’ in your for loop to your ‘score’ vector (that you have already preallocated), index it:
score=zeros(1, again);
for j=1:again
[...]
while(..)
[...]
end
score(j)=tries;
end

Más respuestas (1)

Niraj Sanghvi
Niraj Sanghvi el 20 de Abr. de 2015
I am assuming that by the phrase "removing the allocation", you do not wish to erase the line:
score = zeros(1,again);
From the use case that you mentioned it seems that you want to store the variable tries from the jth iteration in the jth position of the variable 'score'
You can do this by indexing into the variable score in the following way:
score(j) = tries;
The overall code will look like:
score=zeros(1, again);
for j=1:again
[...]
while(..)
[...]
end
score(j) = tries;
end
Check out this link for more help on indexing http://www.mathworks.com/help/matlab/math/matrix-indexing.html

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by