Problem with logical indexing with arbitrary indices

1 Ansicht (letzte 30 Tage)
Christopher
Christopher am 6 Okt. 2014
Bearbeitet: Iain am 6 Okt. 2014
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.

Antworten (1)

Iain
Iain am 6 Okt. 2014
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 Kommentare
Christopher
Christopher am 6 Okt. 2014
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 am 6 Okt. 2014
Bearbeitet: Iain am 6 Okt. 2014
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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by