How can I set specific Elements of a Matrix to zero without a for loop

Here is my problem:
o= ones(3,3) % Given Matrix
o =
1 1 1
1 1 1
1 1 1
i = [1 2 2]; % column index of o, which should be set to zero
% quantity of rows in o is always exactly the same like length(i)
The result after manipulating matrix o depending on i should be:
o =
0 1 1
1 0 1
1 0 1
My simple solution
for k=1:length(i)
o(k,i(k))=0;
end
How can i do that without a for loop. In fact, the number of rows of matrix o is 10 000.
Thank you very much!

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2015년 6월 2일
편집: Andrei Bobrov 2015년 6월 2일
o= ones(3,3);
ii = [1 2 2];
[m,n] = size(o);
o(sub2ind([m,n],(1:m)',ii(:)')) = 0;
other way
n = 3;
out = ~accumarray([(1:n)',ii(:)],1,[3,3]) + 0;

댓글 수: 1

Great, thank you very much!
I changed
o(sub2ind([m,n],(1:m)',ii(:)') = 0;
into
o(sub2ind([m,n],1:m,ii(:)')) = 0;
Because it seems that for
sub2ind(A,B,C)
B and C, always have to be column vectors.
Do you think sub2ind is faster conpared to using the for loop?
Not yet tried your second solution.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by