Increasing increment values with vector operations

3 ビュー (過去 30 日間)
Ken Lew
Ken Lew 2018 年 6 月 27 日
コメント済み: Ken Lew 2018 年 6 月 27 日
I'm trying to change this code into a single line of code using vector operations,
a = [];
x = 5;
while x <= 15
a(x-4) = x^2;
x = x + 1;
end
Where the sequence is
25,36,49,64,81,100,121,144,169,196,225
and the difference between two numbers are
11,13,15,17,19,21,23,25,27,29
The number difference have a value of 2 between them
My idea was,
a=25:X:225
where X is the increment value, but i found that X should increase by 2 after every number(11,13,15,17,...). How should i go about this?
  2 件のコメント
Jan
Jan 2018 年 6 月 27 日
By the way: a[x-4] = x^2 must be a(x-4) = x^2
Ken Lew
Ken Lew 2018 年 6 月 27 日
Oh right. Changed it, Thanks!

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

採用された回答

Jan
Jan 2018 年 6 月 27 日
This is leaner than your loop:
a = (5:15) .^ 2
  1 件のコメント
Ken Lew
Ken Lew 2018 年 6 月 27 日
Thank you so much ! I wasn't aware you could do this.

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

その他の回答 (1 件)

Ameer Hamza
Ameer Hamza 2018 年 6 月 27 日
difference = 11:2:29;
a = 25+[0 cumsum(difference)]
a =
25 36 49 64 81 100 121 144 169 196 225
  1 件のコメント
Jan
Jan 2018 年 6 月 27 日
+1. Exactly.

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by