Indexing and Checking on a Diagonal

조회 수: 16 (최근 30일)
washer
washer 2014년 7월 1일
댓글: washer 2014년 7월 1일
I'm just getting back into Matlab and am getting tripped up where I'm more familiar with Python or C right now... still brushing the dust off, thanks for any help!
I'm trying to check the values in a diagonal matrix to see if they are non-zero and below a certain threshold with the goal of forcing them to zero. If my 3x3 diagonal matrix is S, I've seen a good way to index a diagonal is
idx = logical(eye(size(S)));
S(idx)
Which will give the values down the diagonal. But I keep getting tripped up on figuring out a nice way to traverse those three values so I can check them and assign them individually. I get that I could assign them all at once by assign S(idx)=value, but how can I index each individually so I can check if it's above/below my threshold?
I know I could also just loop through it and that my be easier/more clear, but I'm darned curious now (and that loop is messy)!
Thanks for any help!

채택된 답변

Jan
Jan 2014년 7월 1일
편집: Jan 2014년 7월 1일
The indexing by eye() gets inefficient for large arrays. Then linear indexing is cheaper:
c = size(S, 1);
idx = 1:c+1:numel(S);
Then:
v = S(idx);
v(v < limit) = 0;
S(idx) = v;
  댓글 수: 1
washer
washer 2014년 7월 1일
Thanks Jan! I saw the indexing by eye and thought it was pretty nifty and "must be a cool/optimal Matlab thing." That advice is exactly what I was looking for!

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2014년 7월 1일
one way
S = randi(200,10);
a = 100; % your threshold
d = diag(S); % if d(ii) >= a then d(ii) = 1; else d(ii) = -1 ;
t = d >= a;
d(t) = 1;
d(~t) = -1;
S(eye(size(S))>0) = d;

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by