MATLAB Answers

Replace numbers into a vector starts at the center? Looking for general format

조회 수: 2(최근 30일)
Fat Man
Fat Man 14 Jun 2019
댓글: Fat Man 14 Jun 2019
Suppose I have a vector vec with the length will be an odd number.
Then I have another vector vec1 with the length is also odd and less than the length of vec.
I want to put the elements of vec1 into vec that starts at the center of vec and go to both sides from the center.
I'm looking for a general format in case when the length is much more larger !!!
How can I do that?
Ex: This is just an example when length(vec) is 5. I know vec(2:4) = vec1
I'm looking for a general format in case when the length is much more larger !!!
vec = 0 0 0 0 0
vec1 = 1 1 1
new_vec = 0 1 1 1 0
Thank you!

  댓글 수: 0

로그인 to comment.

채택된 답변

per isakson
per isakson 14 Jun 2019
편집: per isakson 14 Jun 2019
Run this
%%
vec = [ 0 0 0 0 0 ];
vec1 = [ 1 1 1 ];
new_vec = [ 0 1 1 1 0 ];
%%
len = length( vec );
len1 = length( vec1 );
%%
out = vec;
out( (len+1)/2 - (len1-1)/2 : (len+1)/2 + (len1-1)/2 ) = vec1;
and peek
>> out
out =
0 1 1 1 0
>>

  댓글 수: 1

로그인 to comment.

추가 답변(1개)

Andrei Bobrov
Andrei Bobrov 14 Jun 2019
vec =[0 0 0 0 0 ];
vec1 = [1 1 1];
z = pad(join(string(vec1),''),numel(vec),'both','0');
out = z{:} - '0'

  댓글 수: 1

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by