How do I update array elements through a loop?

14 ビュー (過去 30 日間)
Justin Saxon
Justin Saxon 2021 年 11 月 9 日
回答済み: Steven Lord 2021 年 11 月 9 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by