Preallocating array without adding after the allocating or removing the allocating
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Star Strider
2015-4-20
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
0 个评论
更多回答(1 个)
Niraj Sanghvi
2015-4-20
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!