How do I update array elements through a loop?

15 次查看(过去 30 天)
How do I update an element in array. So I have an array of say 5 zeros:
[00000]
How do I change certain elements of the array one at a time.
What I mean is how do I go from the following:
[0 0 0 0 0 0]
[4 0 0 0 0 0]
[4 1 0 0 0 0]
[4 1 9 0 0 0]
[4 1 9 6 0 0]
[4 1 9 6 2 0]
[4 1 9 6 2 8]
  2 个评论
Sargondjani
Sargondjani 2021-11-9
It is not so clear what you exactly want to do. But maybe this helps?
cross_corr = zeros(1,1999)
%Compute each element:
for ii = 1:size(cross_corr,2)
cross_corr(1,ii) = %your computation comes here
end
Justin Saxon
Justin Saxon 2021-11-9
编辑:Justin Saxon 2021-11-9
Sorry, I included way too much pointless information in the question.
How do I have an array of 5 zeros -----> [0 0 0 0 0]
and update the elements of the arrays one at a time.
So I go through a loop and end up with a variable. I want to plug that variable into element 1 of the array. Then the loop goes back through and the variable is something new and the new variable goes in element 2. This goes on 1999 times. I have the code I just don't know how to replace the zero with my variable. Its something very simple

请先登录,再进行评论。

回答(1 个)

Steven Lord
Steven Lord 2021-11-9
The empty Static method (you'd made a typo and used emtpy instead of empty) creates a 0-by-0 array of the class when called with no input arguments. When called with a size vector or multiple arguments it creates an array of that size (and at least one of the dimensions must be 0.)
Instead of creating a 0-by-0 empty and assigning to elements of it (growing it each time) I'd preallocate the matrix of the appropriate (non-empty) size and then assign to it. The zeros function will let you do this preallocation with each element of the result containing 0.
z = zeros(1, 5)
z = 1×5
0 0 0 0 0
z(3) = 42
z = 1×5
0 0 42 0 0
z(2) = -999
z = 1×5
0 -999 42 0 0
z(5) = NaN
z = 1×5
0 -999 42 0 NaN

类别

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