Replace some values of a vector with another vector which has a different size

조회 수: 1 (최근 30일)
Hello
I've got the vector: source = [ 0 0 1 0 1]
and the vector a = [2 3],
which has a different size to source.
I'd like to replace in the source vector the elements that are equal to 1, with those of vector a.
The final vector b should be: b = [0 0 2 0 3]
Any thoughts on this?
Thank you!

채택된 답변

Thorsten
Thorsten 2015년 4월 29일
편집: Thorsten 2015년 4월 29일
source(source == 1) = a
  댓글 수: 2
pfb
pfb 2015년 4월 29일
However, that changes "source" instead of creating "b", as asked in the question.

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

추가 답변 (2개)

pfb
pfb 2015년 4월 29일
b=zeros(size(source));
b(find(source))=a;
of course this works only if the number of nonzero elements in source are the same as the elements in a.

Stephen23
Stephen23 2015년 4월 29일
편집: Stephen23 2015년 4월 29일
This can be achieved very simply using basic logical indexing:
>> A = [ 0 0 1 0 1];
>> B = [ 2 3];
>> A(A==1) = B
A = 0 0 2 0 3
On my computer this was almost twice as fast compared to using find and zeros.
  댓글 수: 3
James Tursa
James Tursa 2015년 4월 29일
Stephen switched nomenclature. His starting "A" is your "source" his "B" is your "a", and his resulting "A" is your "b".

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

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by