Clear Filters
Clear Filters

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

2 views (last 30 days)
% 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

Accepted Answer

Birdman
Birdman on 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 Comments
jake stan
jake stan on 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 on 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

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!