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

164 views (last 30 days)
if true
% code
end

Answers (3)

John D'Errico
John D'Errico on 10 Feb 2017
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 Comment
Nagaraju chalicheemala
Nagaraju chalicheemala on 10 Feb 2017
sorry sir my intention is adding of new elements to the specified vector having some elements.

Sign in to comment.


KSSV
KSSV on 10 Feb 2017
N = 10 ;
k = zeros(N,1) ;
for i = 1:N
k(i) = i ;
end
You have to be more specific about your purpose.
  1 Comment
Nagaraju chalicheemala
Nagaraju chalicheemala on 10 Feb 2017
sorry sir my intention is adding of new elements to the specified vector having some elements.

Sign in to comment.


Jan
Jan on 10 Feb 2017
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!