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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by