How can I take the values of one array as inputs to check a condition for another array?

1 view (last 30 days)
Say I have an array like A = [1 1 0; 0 1 0] and B = [1 3; 2 2; 2 3] where B are coordinates in A. How can I input B into A to check if these coordinates = 1? In other words, how can I check if A(1,3), A(2,2), and A(2,3) = 1?
  2 Comments
Alexandra Topciov
Alexandra Topciov on 2 Feb 2016
A = [1 1 0; 0 1 0];
B = [1 3; 2 2; 2 3];
for i=1:length(B)
column_1=B(i,1);
column_2=B(i,2);
Answer{i}=A(column_1,column_2)==1;
end
Guillaume
Guillaume on 2 Feb 2016
Edited: Guillaume on 2 Feb 2016
Alexandra, If you're giving an answer, please post them as answers, not comments to the question.
Also, DO NOT use length with a 2d matrix. If B has only one row, your code will break because of the usage of length.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 2 Feb 2016
Edited: Stephen23 on 2 Feb 2016
You can use sub2ind to convert the row and column indices to linear indices:
>> A = [1 1 0; 0 1 0];
>> B = [1 3; 2 2; 2 3];
>> X = sub2ind(size(A),B(:,1),B(:,2));
>> A(X)
ans =
0
1
0
>> all(A(X))
ans = 0

More Answers (0)

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!