How to find array elements that meet a condition defined by an index vector?

Let A be an n by n matrix of 0's. Let L be an n by 1 matrix of integers, which will be used as an index vector. I want to modify the entries of A based on the following rules:
If L(i)=5 and L(j)=5, then A(i,j)=1;
If L(i)=5 xor L(j)=5 (i.e., exatly one of L(i) and L(j) is 5), then A(i,j)=2;
What is the fastest/simplest code to achieve this? I can use a nested for loop for i and j and modify A(i,j) entry by entry. Is there any built in function that I can use?

댓글 수: 2

Can you explain the difference between L(i) & L(j)?
They impose conditions on the first and second index of the matrix.

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

 채택된 답변

It's not clear to me why L is a matrix of integers when the only value you care about is 5. Shouldn't it be a binary matrix?
We're going to transform it in a binary matrix anyway:
%demo data
n = 20;
A = zeros(n);
L = randi([3 6], n, 1);
is5 = L == 5; %binary matrix indicated where 5 are in L
A(is5 & is5') = 1; %assign 1 when L(i) and L(j) are 5
A(xor(is5, is5')) = 2; %assign 2 when L(i) xor L(j) is 5
and looking at the result made me realise that another way to obtain the same is:
A(is5, :) = 2;
A(:, is5) = 2;
A(is5, is5) = 1;

댓글 수: 3

Note that on old releases you will need repmat (or bsxfun?) to expand the vector to an array. The last three lines will work on any release, although those don't take the xor into account.
bsxfun would be more efficient than repmat, but it's been 3 years now that it's not been needed. The bsxfun version:
A(bsxfun(@and, is5, is5')) = 1;
A(bsxfun(@xor, is5, is5')) = 2;
The 2nd version does an or but then overwrite the elements when both are equal, effectively turning it in an xor. I actually prefer the 2nd version, the outcome is more obvious.
You're right, I overlooked the implicit xor. And about bsxfun: a fair number of people still use older releases than 3 years back, and since we weren't provided with explicit information, I thought it would be better to include the remark.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

질문:

2019년 7월 21일

댓글:

2019년 7월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by