Effacer les filtres
Effacer les filtres

Copying and replacing of some values

1 vue (au cours des 30 derniers jours)
Juster
Juster le 9 Oct 2012
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 commentaires
Juster
Juster le 9 Oct 2012
@ 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 le 11 Oct 2012
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

Connectez-vous pour commenter.

Réponses (4)

Babak
Babak le 9 Oct 2012
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 commentaires
Juster
Juster le 12 Oct 2012
Hello Babak, have you any answer for my addittional question you can find above?
Babak
Babak le 12 Oct 2012
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.

Connectez-vous pour commenter.


Thomas
Thomas le 9 Oct 2012
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 le 9 Oct 2012
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 le 9 Oct 2012
c_final = a;
c_final(bsxfun(@plus,b,(0:n)')) = repmat(a(b),n+1,1);

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by