add different number of zeros in the beginning of a matrix

3 ビュー (過去 30 日間)
Praveen Verma
Praveen Verma 2021 年 7 月 20 日
回答済み: Jan 2021 年 7 月 20 日
suppose i have two matrix
A=[1
3
2]
the row index of 1 is 1, 3 is 2 and 2 is 3.
S=[2 3 4 5 6
4 6 8 9 1
2 3 4 5 6
6 5 4 2 1
4 6 8 9 1
2 3 4 5 6 ]
Now i want to insert zeros in the beginning of each row of S. The number of zeros in each row depends upon the index of matrix A and number of rows in which i want to insert zeros depends upon element value matrix A.
For example in matrix A row index of 1 is 1 and value of element is 1 so i want to insert one zero at the beginning of first row of matrix S. Similary in matrix A the row index of 3 is 2 and element value is 3 so i want to insert 2 zeros in next 3 rows (second third and fourth ) in the beginning of matrix S. again in matrix A the row index of 2 is 3 and element value is 2 so i want to insert 3 zeros in next 2 rows (fifth and sixth) in the beginning of matrix S.
finally the result will look like this
S=[0 2 3 4 5 6
0 0 4 6 8 9 1
0 0 2 3 4 5 6
0 0 6 5 4 2 1
0 0 0 4 6 8 9 1
0 0 0 2 3 4 5 6 ]
my actual matrix is very large so plz provide a general solution.
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2021 年 7 月 20 日
It is not possible to make such a numeric array (of irregular size). You can check it by actually copy-pasting on matrix S and it will give you an error.
However, You can make a cell array (if that is an acceptable answer)

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

回答 (1 件)

Jan
Jan 2021 年 7 月 20 日
The output cannot be a matrix, as Dyuman Joshi told you already, because in a matrix all rows must have the same number of elements. With a cell vector:
A = [1; 3; 2];
S = [2 3 4 5 6; ...
4 6 8 9 1 ; ...
2 3 4 5 6 ; ...
6 5 4 2 1; ...
4 6 8 9 1 ; ...
2 3 4 5 6 ];
nZ = repelem(1:numel(A), A);
nS = size(S, 1);
Result = cell(nS, 1);
for k = 1:nS
Result{k} = [zeros(1, nZ(k)), S(k, :)];
end

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by