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

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

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
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

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

Products

Tags

Community Treasure Hunt

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

Start Hunting!