How to loading a vector with values from a logical index

조회 수: 1 (최근 30일)
Timothy Carnahan
Timothy Carnahan 2014년 7월 16일
댓글: Sara 2014년 7월 16일
I have a vector, Vin, of length m. I also have a logical vector, Idx, to select indices to work on (subset size n < m). I can operate on Vin(Idx) and get Vdata of length n. This is all good. But now I want to generate a new Vout vector that is filled with the values from Vdata at the appropriate index. This can be accomplished by the following code snippet.
Vout=zeros(length(Vin));
k = 1;
for j = 1:length(Vin)
if Idx(j)
Vout(j) = Vdata(k);
k = k + 1;
end
end
This seems verbose ? Is there a more efficient or correct way of doing this? i want the output vector to be of length m, not n

답변 (1개)

Sara
Sara 2014년 7월 16일
Vout = Vin(Idx)
  댓글 수: 4
Timothy Carnahan
Timothy Carnahan 2014년 7월 16일
Ah - yes
Vout = zeros(length(Vin));
Vout(Idx)=Vdata;
Sara
Sara 2014년 7월 16일
You may want to do zeros(length(Vin),1), otherwise you get a square matrix instead of a 1d array for Vout

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by