필터 지우기
필터 지우기

substitute every n elements of a vector

조회 수: 3 (최근 30일)
simone clochiatti
simone clochiatti 2015년 8월 30일
답변: Szilárd Ecsenyi 2021년 7월 22일
Hi, I have a vector lets say 24 elements (zeros), and I want to substitute a vector of ones (lets say in this example a vector of two ones) n times (lets say 4 times in this example) starting from an index of the original vector decided by me, examples:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (original vector)
1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 (here substituted 4 times a vector of 2 ones starting form index 1)
0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 (here substituted 4 times a vector of 2 ones starting form index 3)
Is it possible to do simply something like this (possibly without a for)? just having the vector and deciding how many times substitute it, and the index to start? Thank you so much.

채택된 답변

Stephen23
Stephen23 2015년 8월 31일
편집: Stephen23 2015년 8월 31일
It may be that using a loop is actually faster than other solutions, and less obfuscated:
num = 3; % start index
stp = 6; % step size
vec = [1,2,3]; % vector
out = zeros(1,24)
for k = 1:numel(vec)
out(num+k-1:stp:end) = vec(k);
end
out
Displays this in the command window:
>> temp
out =
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
out =
0 0 1 2 3 0 0 0 1 2 3 0 0 0 1 2 3 0 0 0 1 2 3 0
  댓글 수: 1
simone clochiatti
simone clochiatti 2015년 8월 31일
Thank you everyone for the help, but this is the solution that works for me! Thank you very very much Stephen!!

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

추가 답변 (1개)

Szilárd Ecsenyi
Szilárd Ecsenyi 2021년 7월 22일
more faster:
v = 0:1:23;
v(rem(fix(v/3),2) == 0) = 0;
v(v~=0) = 1;

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by