필터 지우기
필터 지우기

Please help me in generating a matrix of ones for a given matrix

조회 수: 2 (최근 30일)
MANISH KUMAR
MANISH KUMAR 2016년 6월 30일
편집: Stephen23 2016년 7월 6일
Suppose if I already have a matrix 'X' having only one '1' in each row 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;
1 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 1 0 0 0 0]
i need a matrix a 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;
1 1 0 0 0 0 0 0 0 0;
0 0 0 0 0 1 1 1 1 0]
code for matrix 'X'is
P = 5; % The number of competitive projects
T = 10; % The number of time periods
D = [4; 5; 3; 2; 4];
excludedcount = D-1;
X = zeros(P,T);
for row = 1:P
rv = [1, zeros(1, T - excludedcount(row) - 1)];
X(row, 1 : (T - excludedcount(row))) = rv(randperm(numel(rv)));
end

채택된 답변

dpb
dpb 2016년 6월 30일
"Dead-ahead" solution is simply
D = [4; 5; 3; 2; 4];
for row = 1:P
ic=find(X(row,:); % the '1' column index
X(row,ic:ic+D-1)=ones(1,D); % insert the ones vector at that location
end
With some thought this could undoubtedly be transformed to use arrayfun and the multiple outputs from find on the array w/o the explicit loop; whether that would be any faster is questionable I'd venture...
  댓글 수: 1
MANISH KUMAR
MANISH KUMAR 2016년 7월 6일
if any row contains zeros only then it shows error in this line
X(row,ic:ic+D(row)-1)=ones(1,D(row));
For example matrix is
Y =
0 1 0 0 0 0 0 0 0 0
0 0 0 1 0 0 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
in this matrix last two rows contains zeros only. So this code doesn't work.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by