how to use for loop by adding the new element in vector
102 views (last 30 days)
Show older comments
if true
% code
end
1 Comment
Stephen23
on 10 Feb 2017
"how to use for loop by adding the new element in vector"
Doing this will be slow. Why not learn how to use MATLAB better and write fast code ?
Answers (3)
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.
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.
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.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!