필터 지우기
필터 지우기

Matrix column selection based on vector with indices

조회 수: 2 (최근 30일)
Dominik Rhiem
Dominik Rhiem 2022년 10월 10일
편집: Torsten 2022년 10월 11일
Hi all. I have a matrix of size m x n, with all entries as one at initialization. I also have a vector of size 1 x m. Each element is supposed to be between 1 and n, and the corresponding matrix entries are set to 0 (i.e. in the m-th matrix row, this is the column given by the m-th element of the vector). The code for that:
mask(sub2ind(size(mask),(1:numel(vector.'))',vector.')) = 0;
However, due to some modifications I had to make to the code, some elements of the vector can now take a value of 0, i.e. an invalid index. I would simply like to skip those elements. How can I do that?

채택된 답변

Torsten
Torsten 2022년 10월 11일
편집: Torsten 2022년 10월 11일
k=ones(6,4);
v=randi(size(k,2),1,size(k,1));
v(end) = 0
v = 1×6
3 2 2 2 1 0
idx = find(v>0)
idx = 1×5
1 2 3 4 5
k(sub2ind(size(k),idx,v(idx))) = 0
k = 6×4
1 1 0 1 1 0 1 1 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 1

추가 답변 (1개)

David Hill
David Hill 2022년 10월 10일
Why not just a simple loop?
k=ones(10,14);
v=randi(size(k,2),1,size(k,1));
for j=1:size(k,1)
k(j,v(j))=0;
end
  댓글 수: 2
Torsten
Torsten 2022년 10월 10일
편집: Torsten 2022년 10월 10일
According to the OP, there can be zeros in the v-vector:
k=ones(3,5);
v=randi(size(k,2),1,size(k,1));
v(end) = 0;
for j=1:size(k,1)
if v(j) > 0
k(j,v(j))=0;
end
end
v
v = 1×3
2 5 0
k
k = 3×5
1 0 1 1 1 1 1 1 1 0 1 1 1 1 1
Dominik Rhiem
Dominik Rhiem 2022년 10월 11일
Hi, thanks for your answers! While that solves the problem, is there maybe a way to do that without a loop?

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by