필터 지우기
필터 지우기

Preallocating array without adding after the allocating or removing the allocating

조회 수: 2 (최근 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.

채택된 답변

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

추가 답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by