Problem with logical indexing with arbitrary indices

조회 수: 1 (최근 30일)
Christopher
Christopher 2014년 10월 6일
편집: Iain 2014년 10월 6일
I have the code:
aarray(find(r(1,1)==1)) = bindices(end);
where aarray is a row vector, r is a matrix, and bindices is another matrix. If r(1,1)==1, I want
aarray(1,end)=bindices(end)
Currently, however, if r(1,1)==1 the argument returns like:
aarray(1,1)=bindices(end)
This makes sense, but I don't know how to modify the code to act on a different element without complications that are probably unnecessary.

답변 (1개)

Iain
Iain 2014년 10월 6일
aarray(find(r(1,1)==1)) = bindices(end);
A. That's not logical indexing.
r(1,1) == 1 can only return a scalar logical 1 or 0. "find" then checks to see if there are any nonzero elements in the input (remember, this is a scalar) and returns the index of the nonzero elements (double format 1 or a double format empty, as the input is a scalar), so your code boils down to either:
aarray(1) = bindices(end); % or
aarray([]) = bindices(end);
The simple answer for what you want is:
if r(1,1) == 1
aarray(1,end) = bindices(end);
end
  댓글 수: 2
Christopher
Christopher 2014년 10월 6일
I know I can use a straightforward conditional, but I want to use vectorized operations. This is because the answer to my question will inform other operations on vectors and matrices, not just scalars. How can I put it all in one vectorized operation? or is that not possible?
Iain
Iain 2014년 10월 6일
편집: Iain 2014년 10월 6일
Its possible. Say for example you have a curve:
x = 0:0.01:2*pi;
y = 5*sin(4*x);
And you want to know where y is negative:
neg_y = find(y < 0);
negs = y<0;
You can then use that to index into x & y to modify them:
x(neg_y) = x(neg_y) *5;
y(negs) = 0;
You can also combine the logic using matrices: (but it's harder to understand)
identity = eye(3);
y = [1 2 3 4 5 6 7 8 9];
y(find(identity)) % gives the result of 1, 5, 9
identity(mod(y,2) == 1) % gives the result of 1 0 1 0 1

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by