Filter löschen
Filter löschen

Preallocating array without adding after the allocating or removing the allocating

2 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Star Strider
Star Strider am 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

Weitere Antworten (1)

Niraj Sanghvi
Niraj Sanghvi am 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

Kategorien

Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by