Creating a vector from recursive elements of another vector

1 回表示 (過去 30 日間)
Elyse Lalonde
Elyse Lalonde 2020 年 10 月 6 日
回答済み: Peter O 2020 年 10 月 6 日
Say I create a matrix A (1, 100) and want to create a matrix B whose entries are b_i = a_i * a_(i+1), meaning it would be (1,99)
How would I go about this? Im new to MATLAB and this is puzzling me.
Thanks.

採用された回答

Peter O
Peter O 2020 年 10 月 6 日
Welcome to MATLAB!
Matlab will allocate the memory for you on the fly, so this is a one line operation, no need for a loop :)
Use the colon to mark a continuous range of indices. For your question:
B = A(1,1:99).*A(1,2:100)
Note that the .* operator is used to mark element-wise multiplication, otherwise, you're trying to multiply [1x99] x [1x99], which isn't compatible and you'll receive an error. There are similar element-wise operations for exponentiation (.^) and division (./)
You can also go backwards, skip indices, and access a subset by using two colons for the range:
B = A(1, 1:99) .* A(1,100:-1:2) % Backwards
B = A(1, 1:3:99) .* A(1,2:3:100) % Every 3rd
B = A(1, [3,4,5]) .* A(1,[51,61,71]) % A subset of values having equal array dimensions
B = A(1, 1:end-1) .* A(1, 2:end); % Use the "end" keyword with add/subtraction to have flexible code without needing to query the matrix length

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by