Effacer les filtres
Effacer les filtres

How do I add a value to an adjacent element without for loop

2 vues (au cours des 30 derniers jours)
jake stan
jake stan le 23 Mar 2018
Commenté : Birdman le 23 Mar 2018
% x = zeros(1,7)
x(1) = 3
x(2) = 4
lengthofx = length(x)
x(3:end) = x(2:end-1)+1
I was wondering how to add a value to a next element without for loop? I'm given x(1) = 3, and x(2) is 4, and
I'm trying to add one to the next element so add 1 to element 3, then add 1 to element 3, and so on but this part
doesn't work: x(2:end) = x(1:end-1)+1.
It adds one to element 3 which becomes 5, but then when it reaches to element 4 it just adds 1 to it, so the element value is one instead of 6

Réponse acceptée

Birdman
Birdman le 23 Mar 2018
Try this:
x=zeros(1,7);
x(1)=3;
x(2)=4;
x(find(x==0,1,'first'):end)=x(find(x~=0,1,'last'))+1:x(find(x~=0,1,'last'))+sum(x==0)
  5 commentaires
jake stan
jake stan le 23 Mar 2018
Oh it doesn't work when I want to change the addition value, so instead of adding one it adds like 6 or any number
Birdman
Birdman le 23 Mar 2018
Ok, try this: By changing N, you will add any value you want,
x=zeros(1,9);
x(1)=3;
x(2)=4;
N=6
x(find(x==0,1,'first'):end)=(x(find(x==0,1,'first'))+1:N:N*(x(find(x==0,1,'first'))+sum(x==0)))+x(find(x~=0,1,'last'))-1+N

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by