How do I update array elements through a loop?

15 views (last 30 days)
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 Comments
Sargondjani
Sargondjani on 9 Nov 2021
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 on 9 Nov 2021
Edited: Justin Saxon on 9 Nov 2021
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

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 9 Nov 2021
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

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!