フィルターのクリア

How to create a vector with for loop?

18 ビュー (過去 30 日間)
Hamzah Faraj
Hamzah Faraj 2020 年 5 月 14 日
編集済み: Hamzah Faraj 2020 年 5 月 14 日
Hello,
I am trying to devide the values between a vector elements by 0.1. Assume x = [1,4,-1,5,0,-2]. I want to create a vector with that:
If x(k) > x(k-1) : increment by 0.1 ----> x(k-1) : 0.1 : x(k)
if x(k) < x(k-1) : decrement by 0.1 ----> x(k-1) : -0.1 : x(k)
In my attempt, it only shows the results between last two elements (0 and -2), but I need the values for the elements.
Any help is appreciated. Thanks!
x = [1,4,-1,5,0,2];
for k=2:length(x)
if x(k) > x(k-1)
vt = v(k-1):0.1:v(k);
else
vt = x(k-1):-0.1:x(k);
end
end

採用された回答

Geoff Hayes
Geoff Hayes 2020 年 5 月 14 日
Hamzah - on each subsequent iteration of your loop, you are overwriting the data from the previous iteration since you are setting vt to something new. You need to concatenate the new data with the previous data so that you don't lose anything. Try the following:
x = [1,4,-1,5,0,2];
vt = [];
for k=2:length(x)
if x(k) > x(k-1)
vt = [vt x(k-1):0.1:x(k)];
else
vt = [vt x(k-1):-0.1:x(k)];
end
end
  1 件のコメント
Hamzah Faraj
Hamzah Faraj 2020 年 5 月 14 日
編集済み: Hamzah Faraj 2020 年 5 月 14 日
Thank you Geoff Hayes. It does return the required results.

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

その他の回答 (0 件)

カテゴリ

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