Clear Filters
Clear Filters

Preallocating array without adding after the allocating or removing the allocating

2 views (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 20 Apr 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

More Answers (1)

Niraj Sanghvi
Niraj Sanghvi on 20 Apr 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

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!