Problem with logical indexing with arbitrary indices
Show older comments
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.
Answers (1)
Iain
on 6 Oct 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 Comments
Christopher
on 6 Oct 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
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!