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

94 次查看(过去 30 天)
if true
% code
end

回答(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.

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.

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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by