add different number of zeros in the beginning of a matrix
3 views (last 30 days)
Show older comments
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 Comment
Dyuman Joshi
on 20 Jul 2021
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)
Answers (1)
Jan
on 20 Jul 2021
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
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!