Hello,
I'm trying to vectorize something like this:
z=zeros(3); x=[1 2 3]; y=x;
for i=1:length(x) %or y, doesn't matter
z( x(i),y(i) )=z( x(i),y(i) ) + 1;
end
So
z= [1 0 0 ; 0 1 0 ; 0 0 1]
What I really want is to do it for any x and y vectors in a 1000by1000 zero matrix.
I tried to do:
z(x,y)=z(x,y)+1;
But I get all values of z =1. I also tried:
z(x.,y.)=z(x.,y.)+1;
But an error message appears.
Thanks for your help.

 채택된 답변

Matt J
Matt J 2015년 8월 19일
편집: Matt J 2015년 8월 19일

0 개 추천

idx=sub2ind(size(z),x,y);
z(idx)=z(idx)+1;

댓글 수: 2

Felix Lauwaert
Felix Lauwaert 2015년 8월 19일
Error using sub2ind (line 52) Out of range subscript.
Felix Lauwaert
Felix Lauwaert 2015년 8월 19일
idx=sub2ind([length(x),length(x)],x,y); z(idx)=z(idx)+1;
Is working. Thanks!

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

추가 답변 (0개)

카테고리

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

제품

질문:

2015년 8월 19일

댓글:

2015년 8월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by