how to use for loop by adding the new element in vector

답변 (3개)

John D'Errico
John D'Errico 2017년 2월 10일
This is something you do not want to do. Why not? because the very next time you ask a question on Answers, it will be a frantic "Why is my code so slow?"
What happens is MATLAB reallocates memory for the entire array, EVERY time you add a new element. Then it must move ALL of your data to the new memory location for the new array. This takes longer and longer on each iteration. It is said to grow quadratically with the size of the array.
This is why we strongly suggest that you PREALLOCATE such arrays with zero (or NaN) elements at the expected final size they will be. Then just stuff each element in one at a time, replacing the zero elements. Personally, I like the idea of using NaNs as the initial elements.
Thus, if you know the final size of your array will be 100, then just do this:
A = NaN(1,100);
for k = 1:100
A(k) = something
end
Now A is never grown with time, and the code will be very fast, with no reallocation problems at all.

댓글 수: 1

sorry sir my intention is adding of new elements to the specified vector having some elements.

댓글을 달려면 로그인하십시오.

KSSV
KSSV 2017년 2월 10일
N = 10 ;
k = zeros(N,1) ;
for i = 1:N
k(i) = i ;
end
You have to be more specific about your purpose.

댓글 수: 1

sorry sir my intention is adding of new elements to the specified vector having some elements.

댓글을 달려면 로그인하십시오.

Jan
Jan 2017년 2월 10일
The question is not clear. Perhaps you want something like this:
x = rand(1, 100);
for k = 1:numel(x)
x(k) = x(k) + sin(k); % For example
end
What does "adding" exactly mean? Appending or the plus operation? Please post a small example with inputs, explanations and the wanted output.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2017년 2월 10일

답변:

Jan
2017년 2월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by