How to create a matrix whose elements are a function of previous elements

I have an initial matrix of [1 2 4; 1 4 3] and am wanting to have this matrix gain additional rows by a certain amount given by the user wherein for each additional row, the values of the elements on that row are +2 from the values two rows before. So 2 additional rows from the initial matrix would provide [1 2 4; 1 4 3; 3 4 6; 3 6 5].

 採用された回答

Adam Danz
Adam Danz 2023 年 1 月 5 日
編集済み: Adam Danz 2023 年 1 月 5 日
This solution has two "inputs", initialMatrix and nRows and produces the output matrix out which has the same number of rows specified by nRows (unless nRows is less than the number of rows in the initial matrix).
% Inputs
initialMatrix = [1 2 4; 1 4 3]; % must have at least 2 rows
nRows = 7; % number of desired rows in the output matrix
% compute additional rows
nRowsToAdd = nRows - height(initialMatrix);
padlength = nRowsToAdd+mod(nRowsToAdd,2); % will be even
delta = repelem((2:2:padlength)',2,1);
lastRows = repmat(initialMatrix(end-1:end,:), padlength/2, 1);
resultMatrix = lastRows + delta;
% Output
out = [initialMatrix; resultMatrix(1:nRowsToAdd,:)]
out = 7×3
1 2 4 1 4 3 3 4 6 3 6 5 5 6 8 5 8 7 7 8 10

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

リリース

R2022a

タグ

質問済み:

2023 年 1 月 5 日

編集済み:

2023 年 1 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by