Produce equality matrix based on elements in vector.

조회 수: 3 (최근 30일)
Alexander Holmes
Alexander Holmes 2020년 3월 27일
답변: darova 2020년 3월 27일
Given two equally sized vectors A and B, is there any way to make a matrix C of 1's and zero's such that the kth row of C contains 1's wherever elements of B equal the kth element of A?
I can do it by looping through elements of A, but I want to know if there's a vectorised way of doing this to speed it up?
  댓글 수: 2
Alexander Holmes
Alexander Holmes 2020년 3월 27일
편집: Alexander Holmes 2020년 3월 27일
Actually, think I figured out an answer. I can just use repmat to create a matrix of n copies of the vector, and use == with the vector to compare it that way.
Guillaume
Guillaume 2020년 3월 27일
"I can just use repmat"
You don't need repmat. Implicit expansion will take care of repeating the elements for you and will be faster. See my answer.

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

채택된 답변

Guillaume
Guillaume 2020년 3월 27일
Trivially done.
%assuming A and B are both row vectors:
C = A.' == B;
If they're both column vectors, transpose B instead.
  댓글 수: 1
Alexander Holmes
Alexander Holmes 2020년 3월 27일
Ah yeah, that does it perfectly. That's a much better method.
Thank you!

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

추가 답변 (3개)

Fangjun Jiang
Fangjun Jiang 2020년 3월 27일
Like this?
A=randi(10,5,1);
B=randi(10,5,1);
k=3;
C=(B==A(k))

Bernd Wagner
Bernd Wagner 2020년 3월 27일
Does the Logical opperator C= A==B not do that work?
It compares values in Vector A and responds a logical value 1 if the Value is also on the same line in B. Hence your C vector will be a vector of 0 and 1 with 1 if A==B.
  댓글 수: 1
Alexander Holmes
Alexander Holmes 2020년 3월 27일
That wasn't quite what I wanted. I wantred to compare the whole vector to each element of another vector, which would give me a matrix at the end rather than a vector. But the user above has given me what I needed.
Thank you though!

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


darova
darova 2020년 3월 27일
Try bsxfun
% make all combinations using bsxfun
C = bsxfun(@minus,b(:),a(:)'); % b - rows, a - columns
[i,j] = find(~C); % find 'zero'
C1 = C*0;
C1(i,:) = 1; % make entire row '1' if any element a==b

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by