Create an alternating matrix

5 ビュー (過去 30 日間)
John Carroll
John Carroll 2022 年 11 月 30 日
コメント済み: John Carroll 2022 年 11 月 30 日
Hello. I am looking to create a 1xn matrix where I would enter a max value and a step size for the vector where each value alternates sign. For example I would enter a max value of 20 and a step size of 5 and the result would produce the following matrix;
[0 5 -5 10 -10 15 -15 20 -20]
Thank you in advance.

採用された回答

DGM
DGM 2022 年 11 月 30 日
編集済み: DGM 2022 年 11 月 30 日
There are many ways. Here's one.
% parameters
st = 5;
ev = 20;
A = [0 kron(st:st:ev,[1 -1])]
A = 1×9
0 5 -5 10 -10 15 -15 20 -20
Here's another:
B = repmat(0:st:ev,[2 1]).*[1; -1];
B = B(2:end)
B = 1×9
0 5 -5 10 -10 15 -15 20 -20
Here's another:
C = [0 repelem(st:st:ev,2)];
C(3:2:end) = -C(3:2:end)
C = 1×9
0 5 -5 10 -10 15 -15 20 -20
  1 件のコメント
John Carroll
John Carroll 2022 年 11 月 30 日
This works prefectly. I was completely unaware of the kron command. Thank you.

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

その他の回答 (1 件)

VBBV
VBBV 2022 年 11 月 30 日
maxV = 20;
stepS = 5;
I = zeros(1,2*(maxV/stepS)+1);
I1 = 0:stepS:maxV;
I2 = -I1(2:end);
I(1:2:end) = I1;
I(2:2:end) = I2;
I
I = 1×9
0 -5 5 -10 10 -15 15 -20 20
  1 件のコメント
John Carroll
John Carroll 2022 年 11 月 30 日
This works great as well. Thank you.

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by