필터 지우기
필터 지우기

Please help me in inserting ones in a given matrix in special rows

조회 수: 1 (최근 30일)
MANISH KUMAR
MANISH KUMAR 2016년 7월 6일
댓글: Stephen23 2016년 7월 6일
Suppose if I already have a matrix 'X' having only one '1' in few rows and other rows contains zeros only for example matrix given below
X =
[0 0 0 0 1 0 0 0 0 0;
0 1 0 0 0 0 0 0 0 0;
0 0 1 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0]
i need a matrix having few (specified number) '1's after existing '1' in each row.
for example output matrix is
Y =
[0 0 0 0 1 1 1 1 0 0;
0 1 1 1 1 1 0 0 0 0;
0 0 1 1 1 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0]
number of ones to be inserted in specified rows are D = [4; 5; 3; 2; 4];
as in example matrix last two rows are zeros only, there is no need to insert ones in those rows,as there is no '1' appearing in those rows

답변 (2개)

Stephen23
Stephen23 2016년 7월 6일
편집: Stephen23 2016년 7월 6일
MATLAB is a high-level language, so there is no need to waste time with ugly loops as if this was some poor low-level language like C++. Vectorized code is much neater:
>> tmp = cumsum(cumsum(X,2),2);
>> Y = bsxfun(@le,tmp,D) & tmp
Y =
0 0 0 0 1 1 1 1 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

José-Luis
José-Luis 2016년 7월 6일
X = [0 0 0 0 1 0 0 0 0 0;
0 1 0 0 0 0 0 0 0 0;
0 0 1 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0]
D = [4; 5; 3; 2; 4];
for row = 1:numel(D)
ic = find(X(row,:));
if ~isempty(ic)
X(row,ic:ic+D-1)= 1;
end
end

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by