How can I add on to y in a for loop? Insert zeros into vector. cody question

2 ビュー (過去 30 日間)
A C
A C 2018 年 8 月 5 日
コメント済み: A C 2018 年 8 月 5 日
The code returns 5 0 0.
I used the debugger. The for loop made 1 0 0; 2 0 0;....; 5 0 0
The goal is to return y = [1 0 0 2 0 0 3 0 0 4 0 0 5 0 0]
x = [1 2 3 4 5];
n = 2;
% zero = zeros(1,n)
% [x(1) 0 0 x(2) 0 0]
y = [];
zero=zeros(1,n);
% How can I combine y?
for i = 1:1:length(x)
y = [x(i),zero]
end
  1 件のコメント
Walter Roberson
Walter Roberson 2018 年 8 月 5 日
You are overwriting all of y in each iteration of your "for" loop.

サインインしてコメントする。

採用された回答

Jan
Jan 2018 年 8 月 5 日
編集済み: Jan 2018 年 8 月 5 日
A hint:
y = [1,2,3]
Then how do you create this output:
[1,2,3,6,7,8]
? Do you see it? You need to include the former value of y.
Another idea:
Create the vector of zeros at first, which has (n+1)*length(x) elements. Then use this as index:
1 + (0:length(x)-1)) * (n + 1)
or equivalently (find out, why this creates the same result!)
1:(n+1):length(y)
when y is the created vector of zeros.
  1 件のコメント
A C
A C 2018 年 8 月 5 日
It works when I added y. When you put y there, it stores every cycle? y = [y,x(i),zero];

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by