Copying and replacing of some values

조회 수: 2 (최근 30일)
Juster
Juster 2012년 10월 9일
Hello to everyone,
I would build a function that has to scan all the 'a' vector and in correspondence of the indexes given in 'b' has to create a new vector with almost the same values of 'a' exepted for elements that go from a(2) to a(2+n)changing it with the same value of a(2). The same for a(8) and the values from a(8)to a(8+n) changing these 4 values with the value a(8). Maybe looking at the 'c_final' vector (what I would like to find!!!) could help you better than what I've tried to explain.
a=[1 5 7 11 14 15 16 12 90 33 46 78 79 66];
b=[2 8];
n = 3;
c_final = [1 5 5 5 5 15 16 12 12 12 12 78 79 66];
Thanks in advance and Best regards.
  댓글 수: 2
Juster
Juster 2012년 10월 9일
@ Tom = Your solution works fine. @ Babak = Also your solution works fine. @ José-Luis = This function is a bit tricky for me, and give me a final vector longer and different than request(20 > 14) @ Jonathan Sullivan = Unfortunat. also this solution give me a different final vector but it could be a good idea
But let me some time to check it better and I will let you know what will be the best solution.
With best regards,
Jaster
Juster
Juster 2012년 10월 11일
Hello guys,
I would ask you just a little function modification.
Instead of change al the next 'n' value with the first one, I'd like to change it with the previous value.
For example : c_final(3) = c_final(2) ....c_final(4) = c_final(3) etc.
Thanks in advance,
Jaster

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

답변 (4개)

Babak
Babak 2012년 10월 9일
a=[1 5 7 11 14 15 16 12 90 33 46 78 79 66];
b=[2 8];
n=3;
c = a;
for j=1:length(b)
if length(a)>b(j)
index = b(j);
c(index:index+n)=a(index);
end
end
c = c(1:length(a));
c
  댓글 수: 2
Juster
Juster 2012년 10월 12일
Hello Babak, have you any answer for my addittional question you can find above?
Babak
Babak 2012년 10월 12일
Your question you mean c_final(3) = c_final(2) ....c_final(4) = c_final(3) ?
I don't understand it well. Give an example please.

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


Thomas
Thomas 2012년 10월 9일
Another way
c=a;
for ii=1:length(b)
c(find(c==c(b(ii))):find(c==c(b(ii)))+n)=c(b(ii));
end
c

Jonathan Sullivan
Jonathan Sullivan 2012년 10월 9일
It's a little bit of a round about way, but you could leverage MATLAB's strrep function.
c = char(a);
for ii = 1:length(b)
c = strrep(c,aorig(b(ii)),char(repmat(aorig(b(ii)),1,n)));
end
c = double(c);

Andrei Bobrov
Andrei Bobrov 2012년 10월 9일
c_final = a;
c_final(bsxfun(@plus,b,(0:n)')) = repmat(a(b),n+1,1);

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by